2
我正在嘗試跟隨Rob Pike的Google I/O 2012會談,名爲「Go Concurrency」。我正在嘗試通道複用的例子,因此「Ann」和「Joe」不會以鎖步方式進行交談。但是使用下面的代碼,它們仍然是鎖步。我哪裏錯了?爲什麼此Google I/O 2012併發示例不能按預期工作?
視頻: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
}
而這個的(去版本go1.0.2在Ubuntu 10.04 LTS)的輸出
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...
哪兒我去錯了嗎?謝謝!