我正在尝试跟随 Rob Pike 的 Google I/O 2012 演讲“Go Concurrency”。我正在尝试多路复用频道的示例,因此“Ann”和“Joe”不会步调一致。但是使用下面的代码,它们仍然是锁步的。我哪里错了?
视频:http ://www.youtube.com/watch?v=f6kdp27TYZs&feature=player_detailpage#t=1025s
package main
import (
"fmt"
"time"
"math/rand"
)
func fanIn(input1, input2 <-chan string) <-chan string {
c := make(chan string)
go func() { for {c <- <-input1 } }()
go func() { for {c <- <-input2 } }()
return c
}
func main() {
c := fanIn(boring("Joe"), boring("Ann"))
for i:=0; i<10; i++ {
fmt.Println(<-c)
}
fmt.Printf("You're both boring, I'm leaving...\n")
}
func boring(msg string) <-chan string {
c := make(chan string)
go func() { // launch goroutine from inside the fn
for i:=0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond )
}
}()
return c
}
以及这个的输出(Ubuntu 10.04 LTS 上的 go1.0.2 版本)
Joe 0
Ann 0
Joe 1
Ann 1
Joe 2
Ann 2
Joe 3
Ann 3
Joe 4
Ann 4
You're both boring, I'm leaving...
我哪里做错了?谢谢!