gpt4 book ai didi

go - 为什么我的代码在不关闭 channel 的情况下处于死锁状态?

转载 作者:行者123 更新时间:2023-12-01 20:25:50 24 4
gpt4 key购买 nike

我正在尝试编写一个程序:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com