Search code examples
gogoroutine

Issue with fmt.Println not consistent with thread printing order


Consider the following code

package main

import (  
    "fmt"
    "runtime"
    "sync"
)

func main() {
    messages := make(chan bool)
    var wg sync.WaitGroup
    var x = 1000

    wg.Add(runtime.NumCPU())
    for i := 0; i < runtime.NumCPU(); i++ {
        go func(x int) {
            defer wg.Done()
            var i = 0
            for i < x {
                i += 1
                fmt.Println(i * i)
            }
            messages <- true
        }(x)
    }

    go func() {
        for i := range messages {
            fmt.Println(i)
        }
    }()

    wg.Wait()
}

And the following last couple of line output

980100
982081
984064
true
988036
990025
992016
994009
996004
998001
1000000

Since message <- true is always at the end of a for loop and

    for i := range messages {
        fmt.Println(i)
    }

prints after the channel receive the message.

I expect true to be printed always at the end like

988036
990025
992016
994009
996004
998001
1000000
true

But I find that is only sometimes true, why is that?


Solution

  • What you're doing is:

    1. Start a number of goroutines, equal to the number of CPUs on your system.
    2. Start one additional goroutine, which reads and prints the values from the messages channel.
    3. Wait for the goroutines from #1 to terminate
    4. Exit

    Because you're only waiting for the first batch of goroutines to terminate, there is no guarantee that all (or even any) of the messages values will be printed before the program terminates.