我很難理解緩衝通道的工作原理。基於下面的例子中,我試圖利用2個線程同時打印出當前時間,大約有2第二延遲每2去電話之間:需要幫助瞭解緩衝通道
package main
import "fmt"
import "time"
func main() {
returnCurrentTime := func() string {
return time.Now().String()
}
c := make(chan string, 2)
asyncReturnCurrentTime := func(c chan string) {
time.Sleep(2001 * time.Millisecond)
c <- returnCurrentTime()
}
for i := 1; i != 7; i++ {
go asyncReturnCurrentTime(c)
if(i % 3 == 0) {
fmt.Println(<- c)
fmt.Println(<- c)
fmt.Println(<- c)
fmt.Println()
}
}
}
這將產生
2013-02-27 03:17:50
2013-02-27 03:17:50
2013-02-27 03:17:50
2013-02-27 03:17:52
2013-02-27 03:17:52
2013-02-27 03:17:52
什麼我期待關於秒是有史以來二去電話產生以下結果
2013-02-27 03:17:50
2013-02-27 03:17:50
2013-02-27 03:17:52 <- 3rd call with 2 buffer slots
2013-02-27 03:17:54
2013-02-27 03:17:54
2013-02-27 03:17:56 <- 3rd call with 2 buffer slots
顯然我誤解緩衝瓚的概念之間,在這種情況下,2個第二延遲nels,請有人請我解釋我的邏輯中的錯誤,以及如何達到預期的結果?
謝謝
您有更多的兩個「線程」。在這種情況下,每個例程都像一個線程一樣工作,所以在某一時刻,您正在運行三個例程加上主線程,這樣就有四個「線程」。 – masebase 2013-02-27 02:54:23