Noob on channels in Go -


i'm trying wrap head around concurrency patterns in go , confused example #69

package main  import "fmt"  func fibonacci(c, quit chan int) {     x, y := 0, 1     {         select {         case c <- x:             x, y = y, x+y         case <-quit:             fmt.println("quit")             return         }     } }  func main() {     c := make(chan int)     quit := make(chan int)     go func() {         := 0; < 10; i++ {             fmt.println(<-c)         }         quit <- 0     }()     fibonacci(c, quit) } 

in particular, don't see how

for := 0; < 10; i++ {     fmt.println(<-c)  } 

is supposed work, since did make channel, , "receive" 10 times? tried out other code create channel , try receive right away , error, seems work , can't quite see how. help!

i’m giving shorter version of code above, think should easier understand. (i explain differences below.) consider this:

// http://play.golang.org/p/5crbsu4wxd package main  import "fmt"  func fibonacci(c chan int) {     x, y := 0, 1     {         c <- x         x, y = y, x+y     } }  func main() {     c := make(chan int)     go fibonacci(c)      := 0; < 10; i++ {         fmt.println(<-c)     } } 

this more straightforward version because main function printing 10 values channel, , exiting; , there background goroutine filling channel long new value needed.

this alternate version drops quit channel, because background goroutine dies when main() finishes (no need kill explicitly in such simple example).

of course version kills use of select{}, topic of #69. seeing how both versions accomplish same thing, except killing of background goroutine, can perhaps aid in understanding select doing.

note, in particular, if fibonacci() had time.sleep() first statement, loop hang time, work.

hope helps!

p.s.: realized version simpler version #68, i’m not sure how it’ll help. oops. :-)


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -