为什么我的golang频道会引发死锁错误?

为什么我的golang频道会引发死锁错误?,第1张

为什么我的golang频道会引发死锁错误?

之所以陷入僵局,是因为结构是通过值而不是通过引用传递的。

将WaitGroup传递给函数时,需要传递 指针 而不是值。否则,将使用WaitGroup的副本。

这是您的工作示例:

package mainimport (    "fmt"    "sync")func push(c chan int,wg *sync.WaitGroup) {    for i := 0; i < 5; i++ {        c <- i    }    wg.Done()}func pull(c chan int,wg *sync.WaitGroup) {    for i := 0; i < 5; i++ {        result,ok := <- c        fmt.Println(result,ok)    }    wg.Done()}func main() {    var wg sync.WaitGroup    wg.Add(2)    c := make(chan int)    go push(c,&wg)    go pull(c,&wg)    wg.Wait()}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5476445.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存