"A Tour of Go": Possible race condition in the demo code in Go routines

Hi,

Under the topic “Range and Close” under the heading “A Tour of Go” at the location https://tour.golang.org/concurrency/4 we have the following code:

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
    }
    close(c)
}

func main() {
    c := make(chan int, 10)
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}

In my humble opinion, I see a race condition between the main thread (go routine running main() function) and fibonacci thread (go routine running fibonacci(...) function):

As soon as go fibonacci (...) is called in the main thread it continues to execute the for loop (for i:=range c...); it is possible that go fibonacci (...) has not completed yet and therefore, “range c” might be at some intermediate point when the main thread has reached to execute it which is a certain race condition!

Please correct me if I am wrong, and enlighten me with correct understanding especially how there is no race condition between the two threads (go routines).

Sincerely,
M. Nawazish. Khan

There is no race condition as a channel is concurrency safe. The range over the channel picks up values from it until it’s closed, which happens when the value generating routine is done.

Hey @nawazish-gopher, if you ever think you might have a race condition in your Go code, run it with the race detector (e.g. go run -race main.go) and see what output you get.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.