2 回答

TA貢獻1936條經驗 獲得超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)
第二個程序將發送拆分到它自己的執行行中,所以現在我們有:
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
由于這兩條執行線可以獨立工作,因此主線可以下到通道fmt.Println并嘗試從通道接收。第二個線程將等待發送直到發送完畢。

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