我正在閱讀/工作Go Concurrency Patterns: Pipelines and cancel,但我無法理解停止短部分。我們有以下功能:func sq(in <-chan int) <-chan int { out := make(chan int) go func() { for n := range in { out <- n * n } close(out) }() return out}func gen(nums ...int) <-chan int { out := make(chan int) go func() { for _, n := range nums { out <- n } close(out) }() return out}func merge(cs ...<-chan int) <-chan int { var wg sync.WaitGroup out := make(chan int, 1) // enough space for the unread inputs // Start an output goroutine for each input channel in cs. output // copies values from c to out until c is closed, then calls wg.Done. output := func(c <-chan int) { for n := range c { out <- n } wg.Done() } wg.Add(len(cs)) for _, c := range cs { go output(c) } // Start a goroutine to close out once all the output goroutines are // done. This must start after the wg.Add call. go func() { wg.Wait() close(out) }() return out}func main() { in := gen(2, 3) // Distribute the sq work across two goroutines that both read from in. c1 := sq(in) c2 := sq(in) // Consume the first value from output. out := merge(c1, c2) fmt.Println(<-out) // 4 or 9 return // Apparently if we had not set the merge out buffer size to 1 // then we would have a hanging go routine. }現(xiàn)在,如果您注意到 line 2in merge,它表示我們chan使用buffer大小為 1的 out ,因為這是未讀輸入的足夠空間。不過,我?guī)缀蹩梢钥隙ǎ覀儜?yīng)該分配chan與buffer大小2.根據(jù)此代碼示例:c := make(chan int, 2) // buffer size 2c <- 1 // succeeds immediatelyc <- 2 // succeeds immediatelyc <- 3 // blocks until another goroutine does <-c and receives 1 由于本節(jié)意味著一個chan的buffer大小3將不會阻止。任何人都可以澄清/幫助我理解嗎?
1 回答

慕工程0101907
TA貢獻1887條經(jīng)驗 獲得超5個贊
程序向通道發(fā)送兩個值并從通道out
讀取一個值out
。未接收到其中一個值。
如果通道沒有緩沖(容量 0),那么其中一個發(fā)送 goroutine 將阻塞,直到程序退出。這是泄漏。
如果創(chuàng)建的通道容量為 1,則兩個 goroutine 都可以發(fā)送到通道并退出。發(fā)送到通道的第一個值由 接收main
。第二個值保留在通道中。
如果 main 函數(shù)沒有從 channel 接收到一個值out
,那么需要一個容量為 2 的 channel 來防止 goroutines 無限期地阻塞。
- 1 回答
- 0 關(guān)注
- 192 瀏覽
添加回答
舉報
0/150
提交
取消