gpt4 book ai didi

go - 为什么我的 golang channel 引发死锁错误?

转载 作者:IT王子 更新时间:2023-10-29 01:06:49 25 4
gpt4 key购买 nike

package main

import (
"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()
}

输出:

localhost:src kuankuan$ go run goroutine.go 
0 true
1 true
2 true
3 true
4 true
throw: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x42130100, 0x42130100)
/usr/local/go/src/pkg/runtime/zsema_amd64.c:146 +0x25
sync.(*WaitGroup).Wait(0x42120420, 0x0)
/usr/local/go/src/pkg/sync/waitgroup.go:79 +0xf2
main.main()
/Users/kuankuan/go/src/goroutine.go:31 +0xb9

goroutine 2 [syscall]:
created by runtime.main
/usr/local/go/src/pkg/runtime/proc.c:221
exit status 2

最佳答案

它死锁的原因是因为结构是按值而不是按引用传递的。

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

这是您的工作示例:

package main

import (
"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()
}

关于go - 为什么我的 golang channel 引发死锁错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13566065/

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