Is it not guaranteed that all statements gets executed in a goroutine?

Issue

There is no error when I run the following code, but nothings gets printed either:

package main

import "fmt"

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    counter := 0
    for {
        
        select {
        case c <- x:
            fmt.Println("sent x", x)
            x, y = y, x+y
        case <-quit:
            fmt.Println("quit")
            return
        }
        
        counter += 1
        fmt.Println("Counter", (counter));
        
    }
    
    fmt.Println("Fib exiting");
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    go func() {
        for i := 0; i < 10; i++ {
            fmt.Println("got" , <-c)
        }
        quit <- 0
        fmt.Println("Anon exiting");
    }()
    go fibonacci(c, quit)
}

I was thinking at least "Fib exiting" should be printed. If I execute fibonacci() normally in the main goroutine, it works.

Thanks in Advance…

Solution

Is it not guaranteed that all statements gets executed in a goroutine?

All statements that should execute according to your program control flow will execute.

Your fmt.Println("Fib exiting") print call doesn’t execute because main() is returning immediately after spawning the two goroutines.

However even if main() were properly synchronized, fmt.Println("Fib exiting") is still unreachable code, because the select statement in fibonacci() either sends on c or receives on quit, and neither of those cases break out of the loop.

Answered By – blackgreen

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.