2 回答

TA貢獻(xiàn)1936條經(jīng)驗 獲得超7個贊
讓我們逐步完成第一個程序:
// My notes here
ch := make(chan int) // make a new int channel
ch <- 1 // block until we can send to that channel
// keep blocking
// keep blocking
// still waiting for a receiver
// no reason to stop blocking yet...
// this line is never reached, because it blocks above forever.
fmt.Println(<-ch)
第二個程序?qū)l(fā)送拆分到它自己的執(zhí)行行中,所以現(xiàn)在我們有:
ch := make(chan int) // make a new int channel
go func () { // start a new line of execution
ch <- 1 // block this second execution thread until we can send to that channel
}()
fmt.Println(<-ch) // block the main line of execution until we can read from that channel
由于這兩條執(zhí)行線可以獨立工作,因此主線可以下到通道fmt.Println并嘗試從通道接收。第二個線程將等待發(fā)送直到發(fā)送完畢。

TA貢獻(xiàn)1785條經(jīng)驗 獲得超4個贊
go 例程絕對有所作為。寫入通道的 go 例程將被阻塞,直到您的主函數(shù)準(zhǔn)備好從 print 語句中的通道讀取。有兩個并發(fā)線程,一個讀取,一個寫入,滿足雙方的準(zhǔn)備工作。
在您的第一個示例中,單個線程被通道寫入語句阻塞,并且永遠(yuǎn)不會到達(dá)通道讀取。
您需要有一個并發(fā)的 go 例程,以便在您寫入通道時從通道中讀取。并發(fā)與通道使用密切相關(guān)。
- 2 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報