quattad
quattad

Reputation: 13

Go Tour #5: select statement example

I'm new to the Go language and am currently going through the Go tour. I have a question regarding the concurrency example 5 on the select statement.

The code below has been edited with print statements to trace statements execution.

package main

import "fmt"

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    fmt.Printf("Run fib with c: %v, quit: %v\n", c, quit)
    for {
        select {
        case c <- x:
            fmt.Println("Run case: c<-x")
            x, y = y, x+y
            fmt.Printf("x: %v, y: %v\n", x, y)
        case <-quit:
            fmt.Println("Run case: quit")
            fmt.Println("quit")
            return
        }
    }
}

func runForLoop(c, quit chan int) {
    fmt.Println("Run runForLoop()")
    
    for i := 0; i < 10; i++ {
        fmt.Printf("For loop with i: %v\n", i)
        fmt.Printf("Returned from c: %v\n", <-c)
    }
    
    quit <- 0
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    go runForLoop(c, quit)
    fibonacci(c, quit)
}

The following is printed to the console.

Run fib with c: 0xc00005e060, quit: 0xc00005e0c0
Run runForLoop()
For loop with i: 0
Returned from c: 0 // question 1
For loop with i: 1
Run case: c<-x // question 2
x: 1, y: 1
Run case: c<-x // question 2
x: 1, y: 2
Returned from c: 1
For loop with i: 2
Returned from c: 1
For loop with i: 3
// ...

My questions are

Upvotes: 1

Views: 477

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51502

For 1: It prints the result of <-c, which will block until another goroutine writes to it. So your statement is not correct: the select case for c<-x ran, with x=0. It is not the zero value of the chan variable. You will only read the zero-value of the chan type from a channel if the channel is closed, or if you use the two-value form of channel read: value,ok := <-c. When ok=false, value is the zero-value of the channel value type.

For 2: c<-x will execute 10 times, because you read from it 10 times in the for-loop, and only then you are writing to quit, which will enable the second case of the select. What you observe here is the second iteration of the loop.

Upvotes: 1

Related Questions