我正在尝试编写一个程序:
package main
import (
"fmt"
"sync"
)
func main() {
n := 4
resChan := make(chan []int, n)
res := []int{}
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
resChan <- append(res, i)
}(i)
}
wg.Wait()
close(resChan) // code will deadlock without this
for subRes := range resChan {
res = append(res, subRes...)
}
fmt.Printf("%v", res)
}
我认为我有一个缓冲通道,因此对通道的写入不会阻塞。但是,我得到了:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/tmp/sandbox562058728/prog.go:23 +0x14c
有人可以解释为什么代码会这样吗?
慕桂英546537
牛魔王的故事
相关分类