我對 Go 很陌生,我正在嘗試了解無緩沖通道和 goroutines。我有這個代碼:func main() {var waitGroup sync.WaitGroupwaitGroup.Add(3)c := make(chan int)go func() { defer waitGroup.Done() x := 1 res := x * 2 fmt.Println(x, "* 2 = ", res) c <- x}()go func() { defer waitGroup.Done() x := <-c res := x * 3 fmt.Println(x, "* 3 = ", res) c <- x}()go func() { defer waitGroup.Done() x := <-c res := x * 4 fmt.Println(x, "* 4 = ", res)}()waitGroup.Wait()close(c)}所以我希望輸出是:1 * 2 = 21 * 3 = 31 * 4 = 4相反,我得到:1 * 2 = 21 * 4 = 4fatal error: all goroutines are asleep - deadlock!我真的不明白為什么第二個函數(shù)會在第三個函數(shù)之后執(zhí)行。如何在不將通道更改為緩沖通道的情況下獲得結(jié)果。
1 回答

Cats萌萌
TA貢獻1805條經(jīng)驗 獲得超9個贊
您似乎希望<-
操作員關(guān)心 goroutines 的創(chuàng)建順序。這不是承諾的(甚至是不可能的)。如果兩個<-
操作員正在讀取同一個通道,則哪一個得到的值是隨機的。如果你想訂購這個,你需要創(chuàng)建另一個通道,第二個 goroutine 寫入,第三個讀取。
緩沖在這里無濟于事,因為問題不在于它在寫入時阻塞。這是第三個函數(shù)消耗一個值并且不生成一個值,所以第二個函數(shù)沒有什么可讀取的。
- 1 回答
- 0 關(guān)注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消