协程导致死锁。

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

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 &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.

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&#39;s why there&#39;s that extra goroutine above.
	for v := range c {
		fmt.Println(v)
	}
}

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:

确定