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?
What you're doing is:
messages
channel.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.