我很难理解缓冲通道的工作方式。根据以下示例,我尝试一次利用2个线程来打印当前时间,每2个go调用之间大约有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
我期望的秒数是两次通话之间的2秒延迟,在这种情况下,以下结果
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
显然我误解了缓冲通道的概念,请有人能解释一下我的逻辑错误以及如何达到预期的结果吗?
相关分类