go - Why is this Google I/O 2012 concurrency example not working as expected? -


i'm trying follow along rob pike's google i/o 2012 talk called "go concurrency". i'm trying example channels multiplexed "ann" , "joe" don't talk in lock-step. using code below, still lock-stepping. going wrong?

video: 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() { {c <- <-input1 } }()     go func() { {c <- <-input2 } }()     return c }  func main() {     c := fanin(boring("joe"), boring("ann"))     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 inside fn         i:=0; ; i++ {             c <- fmt.sprintf("%s %d", msg, i)             time.sleep(time.duration(rand.intn(1e3)) * time.millisecond )         }     }()     return c } 

and output of (go version go1.0.2 on 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... 

where did go wrong? thanks!

your code fine; tends take little more them out of sync. loop more times , should see them out of lock-step:

for := 0; < 20; i++ { // going 20 enough see     fmt.println(<-c) } 

i got output:

 joe 0 ann 0 joe 1 ann 1 joe 2 ann 2 joe 3 ann 3 joe 4 ann 4 joe 5 ann 5 joe 6 ann 6 ann 7 joe 7 joe 8 joe 9 ann 8 ann 9 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -