英文:
Gorountines causing a deadlock
问题
我正在尝试使用goroutines,并遇到了这个例子-https://go.dev/play/p/mWHUmALk-1_K
但是我遇到了这个错误-fatal error: all goroutines are asleep - deadlock!
我尝试修复了这个问题,但没有成功。请问我该如何解决这个问题?
错误似乎出现在第15行、23行和32行。
英文:
I am trying my hands on goroutines and came up this example - https://go.dev/play/p/mWHUmALk-1_K
But I am having this error - fatal error: all goroutines are asleep - deadlock!
I have tried to fix this but no luck. Please how do I fix this?
The error seem to be on lines 15, 23 and 32.
答案1
得分: 1
问题在于你的程序启动了3个独立的goroutine,它们都向同一个通道发送数据。而你的主goroutine只接收了一次来自该通道的数据。这导致第二次通道发送(ch <- fmt.Sprintf("...
)无限期地阻塞。对于无缓冲通道,你需要进行与发送次数相同的接收操作。
确保接收到所有发送的一种方法是使用通道上的range
循环。
func getLength(dd []string, wg *sync.WaitGroup) {
wg.Add(len(dd))
c := make(chan string)
for _, d := range dd {
d1 := d
go computeLength(d1, c, wg)
}
// 在所有goroutine完成后关闭c,
// 确保下面的for-range循环退出。
go func() { wg.Wait(); close(c) }()
// 使用for-range循环在通道上接收所有发送的数据。
//
// 但请注意,只有当通道关闭或循环内部退出时,
// for-range循环才会退出。
//
// 因此,你可以在wg.Wait()返回后关闭c来退出循环,
// 这就是为什么上面有一个额外的goroutine。
for v := range c {
fmt.Println(v)
}
}
https://go.dev/play/p/BUb7NHrq2B0
英文:
The problem is that your program starts 3 separate goroutines that send to the same channel. And you have only the main goroutine receive from that channel only once. This causes the second channel send (ch <- fmt.Sprintf("...
) to block indefinitely. With unbuffered channels you need to do as many receives as you do sends.
One approach to ensure all sends are received would be to use a range
loop over the channel.
func getLength(dd []string, wg *sync.WaitGroup) {
wg.Add(len(dd))
c := make(chan string)
for _, d := range dd {
d1 := d
go computeLength(d1, c, wg)
}
// close c once all goroutines are done to
// ensure the for-range loop below exits.
go func() { wg.Wait(); close(c) }()
// Use for-range loop on the channel to receive all the sends.
//
// But note that a for-range loop over a channel exits only
// when the channel is closed or the loop is exited from within.
//
// So to exit you can close c once wg.Wait() returns,
// that's why there's that extra goroutine above.
for v := range c {
fmt.Println(v)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论