ある私はゴルーチンとチャネルすべてのゴルーチンが眠ってデッドロック
package main
import (
"fmt"
"math/rand"
"time"
)
func boring(msg string) <-chan string {
c := make(chan string)
go func() {
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c
}
func main() {
c := fanInNew(boring("joe"), boring("anh"))
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
fmt.Println("You both are boring, I am leaving")
}
func fanInNew(input1, input2 <-chan string) <-chan string {
c := make(chan string)
for {
select {
case s := <-input1:
c <- s
case s := <-input2:
c <- s
}
}
return c
}
で遊んしようとしています、私はそれは私にエラーを与えているこのプログラムを実行すると、すべてのゴルーチンは、デッドロック眠っています。
しかし、select
を匿名のgoroutineに入れてもうまく動作します。実施例:
package main
import (
"fmt"
"math/rand"
"time"
)
func boring(msg string) <-chan string {
c := make(chan string)
go func() {
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c
}
func main() {
c := fanInNew(boring("joe"), boring("anh"))
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
fmt.Println("You both are boring, I am leaving")
}
func fanInNew(input1, input2 <-chan string) <-chan string {
c := make(chan string)
go func() {
for {
select {
case s := <-input1:
c <- s
case s := <-input2:
c <- s
}
}
}()
return c
}
あなたはそれの背後にある推論を理解するのを手伝ってもらえますか?
その後、私はgoroutinesに入れたときに 'for'ループをどのように返しますか? ?ありがとう – sks
もう一つの 'chan'と空のstruct、closingチャンネルを渡すことができます。しかし、 'WaitGroups'もうまく動作します – Nevermore
あなたを持って..thanks :) – sks