我很難理解緩沖通道的工作方式。根據以下示例,我嘗試一次利用2個線程來打印當前時間,每2個go調用之間大約有2秒的延遲:package mainimport "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:502013-02-27 03:17:502013-02-27 03:17:502013-02-27 03:17:522013-02-27 03:17:522013-02-27 03:17:52我期望的秒數是兩次通話之間的2秒延遲,在這種情況下,以下結果2013-02-27 03:17:502013-02-27 03:17:502013-02-27 03:17:52 <- 3rd call with 2 buffer slots2013-02-27 03:17:542013-02-27 03:17:542013-02-27 03:17:56 <- 3rd call with 2 buffer slots顯然我誤解了緩沖通道的概念,請有人能解釋一下我的邏輯錯誤以及如何達到預期的結果嗎?
- 1 回答
- 0 關注
- 202 瀏覽
添加回答
舉報
0/150
提交
取消