I recently started with go and I am really confused about the order of execution of this program. I hope I am not asking really trivial questions here.
This is basically #69 in the golang tour, with some Println I have inserted; Link to playground: http://play.golang.org/p/PXDlD3EA2f
func fibonacci(c, quit chan int) {
x, y := 0, 1
fmt.Println("Inside the fibonacci")
for {
select {
case c <- x:
fmt.Println("Inside the for, first case, before reassigning ", x, y)
x, y = y, x+y
fmt.Println("Inside the for, first case, after reassigning ", x, y)
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
fmt.Println("Begin of Main")
c := make(chan int)
quit := make(chan int)
fmt.Println("Before gonig to the func")
go func() {
fmt.Println("Inside go routine")
fmt.Println("Inside go routine... again")
for i := 0; i < 10; i++ {
fmt.Println("Inside go routine and the for, before printing the channel")
fmt.Println(<-c)
}
quit <- 0
}()
fmt.Println("Before calling to fibonacci")
fibonacci(c, quit)
fmt.Println("Closing")
}
In the very verbose output I obtain (see attached image below), there are a couple of things I do not understand:
why is the "Inside the fibonacci" line before the ones in the go routine? Is this because after the go command, the compiler is just reading at the same time inside func and fibonacci?
how do fibonacci and func interact? func is not changing the channel c, so why is fibonacci reacting? Who's changing c?
why inside fibonacci there are 5 prints together every time? Honesty I was expecting only 2.
Output of the function:
Let's take it step by step:
Because your go routine actually starts after you call fibonacci
, the scheduler takes a little bit of time to start, for example if you start a goroutine that calls fmt.Println
and do nothing to wait in main
, the program will exit before it gets executed.
fibonacci
is pushing numbers into the channel, notice this part:
select {
case c <- x: //this is sending x to the channel
That again depends on the scheduler and the fact that fmt.Print*
doesn't lock stdout, the output can happen in any order since it's 2 different threads printing stuff.
Not really an answer, but i found this presentation very handy to understand how channels work: Google I/O 2012 - Go Concurrency Patterns In here you find answers for your questions.