我最近開始學習圍棋,有一個案例我被寫過,我無法理解為什么他會根據僅列印 [第 13 行] 的單行中所做的更改而得到兩種不同的行為,
在第一次運行中,我使用 [第 13 行] 運行程式,然后在主程式中,當我在 [第 21 行] 處列印通道的長度時列印 0,而在下一行中列印 2(我'正在談論主例程所做的第一個列印)。
在第二次運行中,我洗掉了 [第 13 行],然后在第一次列印的兩個列印中,通道的長度為 2。
在圖片中,您可以在控制臺中看到兩個不同的列印件,我不明白它們為什么不同[只是因為添加/洗掉第 13 行]。
// Go behavior that I do not understand /:
package main
import "fmt"
func main() {
mychnl := make(chan string, 2)
go func(input chan string) {
input <- "Inp1"
// If we remove this line the length of the chan in the print will be equal in both prints
fmt.Println("Tell me why D:")
input <- "Inp2"
input <- "Inp3"
input <- "Inp4"
close(input)
}(mychnl)
for res := range mychnl {
fmt.Printf("Length of the channel is: %v The received value is: %s length need to be == ", len(mychnl), res)
fmt.Println(len(mychnl))
}
}
/*
Output ->
Line 13 = fmt.Println("Tell me why D:")
First run with line 13:
Tell me why D:
Length of the channel is: 0 The received value is: Inp1 length need to be == 2
Length of the channel is: 2 The received value is: Inp2 length need to be == 2
Length of the channel is: 1 The received value is: Inp3 length need to be == 1
Length of the channel is: 0 The received value is: Inp4 length need to be == 0
Second run without line 13:
Length of the channel is: 2 The received value is: Inp1 length need to be == 2
Length of the channel is: 2 The received value is: Inp2 length need to be == 2
Length of the channel is: 1 The received value is: Inp3 length need to be == 1
Length of the channel is: 0 The received value is: Inp4 length need to be == 0
*/

uj5u.com熱心網友回復:
您看到的行為是由于競爭條件造成的。通常,您無法確定主 goroutine 何時會列印通道的長度,而其他 goroutine 何時會寫入通道。
通過添加 print 陳述句,您會導致額外的 I/O(到 stdout),這通常意味著 goroutines 產生執行并被重新調度。Print因此,改變 goroutine 寫入通道的速度也就不足為奇了。
在設計帶有通道的程式時,請記住,當通道上發生并發操作時,您不必太在意。當您從通道中讀取時,通道上會出現一、二或零嗎?沒有辦法知道,因為通道是緩沖的,兩個 goroutine 很可能在現代計算機的多核上同時運行。 len()緩沖通道的值可能會導致各種可能的值,并且您不應該依賴它來獲得演算法的正確性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/480229.html
