why the go routine return different result when I change the order or the execution of two go routines that are the same?

70 Views Asked by At

So if we switch the go routine order we get a different result. Why? I added a screenshot with the output and the code.The code is the same in both go routines so it shouldn't change anithing.

func main() {
    ticker := time.NewTicker(1 * time.Second)
    done := make(chan bool)
    sdone := make(chan bool)

    //run first go routine
    go func() {
        for {
            select {
            case <-done:
                fmt.Println("Done one")
            case <-ticker.C:
                fmt.Println("Running one")
            }
        }
    }()

    //run second go routine
    go func() {
        for {
            select {
            case <-sdone:
                fmt.Println("Done second")

            case <-ticker.C:
                fmt.Println("running second")
            }
        }
    }()

    time.Sleep(5 * time.Second)
    ticker.Stop()
    done <- true
    done <- true
    fmt.Println("Tickers stopped")
    //if we switch the order of the run the result is different
}

go routine screenshot

0

There are 0 best solutions below