我最近開始學習 Go,我寫過一個案例,我無法理解為什么他會根據僅打印 [第 13 行] 的一行中所做的更改獲得兩種不同的行為,在第一次運行中,我使用 [第 13 行] 運行程序,然后在主例程中,當我在 [第 21 行] 打印通道長度時打印 0,在下一行打印 2 之后(我'談論主要程序制作的第一個印刷品)。在第二次運行中,我刪除了 [第 13 行],然后在第一次打印時,通道的長度為 2。在圖片中,您可以在控制臺中看到兩個不同的打印件,我不明白為什么它們不同 [只是因為添加/刪除第 13 行]。// Go behavior that I do not understand /:package mainimport "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 == 2Length of the channel is: 2 The received value is: Inp2 length need to be == 2Length of the channel is: 1 The received value is: Inp3 length need to be == 1Length of the channel is: 0 The received value is: Inp4 length need to be == 0Second run without line 13:Length of the channel is: 2 The received value is: Inp1 length need to be == 2Length of the channel is: 2 The received value is: Inp2 length need to be == 2Length of the channel is: 1 The received value is: Inp3 length need to be == 1Length of the channel is: 0 The received value is: Inp4 length need to be == 0*/
1 回答

慕容708150
TA貢獻1831條經驗 獲得超4個贊
您看到的行為是由于競爭條件造成的。通常,與其他協程寫入通道相比,您無法確定主協程何時打印通道長度。
通過添加 print 語句,您會導致額外的 I/O(到 stdout),這反過來通常意味著 goroutines 放棄執行并重新安排。Print
因此,改變您的 goroutine 寫入通道的速度也就不足為奇了。
在設計帶有通道的程序時,請記住,當通道上發生并發操作時,您一定不要太在意。當您從頻道中讀取時,頻道上會出現一、二或零嗎?沒有辦法知道,因為通道是緩沖的,兩個 goroutine 很可能在現代計算機的多核上同時運行。 len()
緩沖通道可能會導致各種可能的值,您不應該依賴它來保證算法的正確性。
- 1 回答
- 0 關注
- 106 瀏覽
添加回答
舉報
0/150
提交
取消