我很难理解缓冲通道的工作方式。根据以下示例,我尝试一次利用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 回答
- 1 回答
- 0 关注
- 179 浏览
添加回答
举报
0/150
提交
取消