我正在嘗試使用 goroutines 并想出了這個例子 - https://go.dev/play/p/mWHUmALk-1_K
但我有這個錯誤 -fatal error: all goroutines are asleep - deadlock!
我試圖解決這個問題,但沒有運氣。請問我該如何解決這個問題?
錯誤似乎在第 15、23 和 32 行。
uj5u.com熱心網友回復:
問題是您的程式啟動了 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)
}
// 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)
}
}
https://go.dev/play/p/BUb7NHrq2B0
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/424137.html
上一篇:如何在VisualStudioCode中配置“staticcheck”linter?
下一篇:命名空間的Golang命名空間
