协程导致死锁。

huangapple go评论115阅读模式
英文:

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循环。

  1. func getLength(dd []string, wg *sync.WaitGroup) {
  2. wg.Add(len(dd))
  3. c := make(chan string)
  4. for _, d := range dd {
  5. d1 := d
  6. go computeLength(d1, c, wg)
  7. }
  8. // 在所有goroutine完成后关闭c,
  9. // 确保下面的for-range循环退出。
  10. go func() { wg.Wait(); close(c) }()
  11. // 使用for-range循环在通道上接收所有发送的数据。
  12. //
  13. // 但请注意,只有当通道关闭或循环内部退出时,
  14. // for-range循环才会退出。
  15. //
  16. // 因此,你可以在wg.Wait()返回后关闭c来退出循环,
  17. // 这就是为什么上面有一个额外的goroutine。
  18. for v := range c {
  19. fmt.Println(v)
  20. }
  21. }

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 &lt;- fmt.Sprintf(&quot;...) 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.

  1. func getLength(dd []string, wg *sync.WaitGroup) {
  2. wg.Add(len(dd))
  3. c := make(chan string)
  4. for _, d := range dd {
  5. d1 := d
  6. go computeLength(d1, c, wg)
  7. }
  8. // close c once all goroutines are done to
  9. // ensure the for-range loop below exits.
  10. go func() { wg.Wait(); close(c) }()
  11. // Use for-range loop on the channel to receive all the sends.
  12. //
  13. // But note that a for-range loop over a channel exits only
  14. // when the channel is closed or the loop is exited from within.
  15. //
  16. // So to exit you can close c once wg.Wait() returns,
  17. // that&#39;s why there&#39;s that extra goroutine above.
  18. for v := range c {
  19. fmt.Println(v)
  20. }
  21. }

https://go.dev/play/p/BUb7NHrq2B0

huangapple
  • 本文由 发表于 2022年2月13日 21:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/71101091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定