我最近開(kāi)始學(xué)習(xí) Go,我寫過(guò)一個(gè)案例,我無(wú)法理解為什么他會(huì)根據(jù)僅打印 [第 13 行] 的一行中所做的更改獲得兩種不同的行為,在第一次運(yùn)行中,我使用 [第 13 行] 運(yùn)行程序,然后在主例程中,當(dāng)我在 [第 21 行] 打印通道長(zhǎng)度時(shí)打印 0,在下一行打印 2 之后(我'談?wù)撝饕绦蛑谱鞯牡谝粋€(gè)印刷品)。在第二次運(yùn)行中,我刪除了 [第 13 行],然后在第一次打印時(shí),通道的長(zhǎng)度為 2。在圖片中,您可以在控制臺(tái)中看到兩個(gè)不同的打印件,我不明白為什么它們不同 [只是因?yàn)樘砑?刪除第 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貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
您看到的行為是由于競(jìng)爭(zhēng)條件造成的。通常,與其他協(xié)程寫入通道相比,您無(wú)法確定主協(xié)程何時(shí)打印通道長(zhǎng)度。
通過(guò)添加 print 語(yǔ)句,您會(huì)導(dǎo)致額外的 I/O(到 stdout),這反過(guò)來(lái)通常意味著 goroutines 放棄執(zhí)行并重新安排。Print
因此,改變您的 goroutine 寫入通道的速度也就不足為奇了。
在設(shè)計(jì)帶有通道的程序時(shí),請(qǐng)記住,當(dāng)通道上發(fā)生并發(fā)操作時(shí),您一定不要太在意。當(dāng)您從頻道中讀取時(shí),頻道上會(huì)出現(xiàn)一、二或零嗎?沒(méi)有辦法知道,因?yàn)橥ǖ朗蔷彌_的,兩個(gè) goroutine 很可能在現(xiàn)代計(jì)算機(jī)的多核上同時(shí)運(yùn)行。 len()
緩沖通道可能會(huì)導(dǎo)致各種可能的值,您不應(yīng)該依賴它來(lái)保證算法的正確性。
- 1 回答
- 0 關(guān)注
- 113 瀏覽
添加回答
舉報(bào)
0/150
提交
取消