我正在阅读/工作Go Concurrency Patterns: Pipelines and cancellation,但我无法理解停止短片部分。我们有以下功能:
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.
}
现在,如果您在2
中注意到行merge
,则表示我们将chan
标记为buffer
,因为这是未读输入的足够空间。但是,我几乎肯定我们应该分配chan
buffer
大小2.根据此代码示例:
c := make(chan int, 2) // buffer size 2
c <- 1 // succeeds immediately
c <- 2 // succeeds immediately
c <- 3 // blocks until another goroutine does <-c and receives 1
因为此部分意味着chan
buffer
大小3不会阻止。任何人都可以澄清/协助我的理解吗?
答案 0 :(得分:1)
程序向通道out
发送两个值,并从通道out
中读取一个值。其中一个值未收到。
如果通道未缓冲(容量为0),则其中一个发送goroutine将阻塞,直到程序退出。这是泄密。
如果创建的通道容量为1,则两个goroutine都可以发送到通道并退出。发送到频道的第一个值由main
接收。第二个值保留在频道中。
如果主函数没有从通道out
接收到值,则需要容量为2的通道来防止goroutine无限期地阻塞。