go - 为什么我的代码在没有关闭通道的情况下陷入僵局?
问题描述
我正在尝试编写一个程序:
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
有人可以解释为什么代码会这样吗?
解决方案
在通道关闭之前,测距通道不会退出 for 循环。
推荐阅读
- oauth-2.0 - 每次我使用 YouTube 数据 API v3 时,如何绕过输入验证码来授权我的代码
- python - PyCharm 在 Mac 上找不到 Tesseract
- reactjs - 如何在 MuiDataTable 的 customBodyRender 中使用 onClick 事件中的值?
- python - discord py我如何为具有ID的服务器成员用户赋予角色
- javascript - FlatList 更新缓慢
- google-analytics - 为什么在 GA 中记录的交易带有(未设置)登陆页面
- vuejs2 - Nuxt 商店 mapGetters 属性在 beforeCreate() 钩子上未定义
- android - E/iardini.error0: 无效 ID 0x00000001 - 错误资源 ID
- pdf - 使用目录呈现 rmarkdown pdf 时出错
- regex - Htaccess - 删除 html 扩展名 + 添加斜杠 + 在子文件夹中查找索引(组合)