我正在尝试编写一个程序:
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)
}
我以为我有一个缓冲的 channel ,因此不会阻塞对该 channel 的写入。但是,我得到了:fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/tmp/sandbox562058728/prog.go:23 +0x14c
有人可以解释为什么代码会这样吗?
最佳答案
在 channel 关闭之前,测距 channel 不会退出for循环。
关于go - 为什么我的代码在不关闭 channel 的情况下处于死锁状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63643641/