Regarding this post As that post mentioned, we don't need to put runtime.Gosched() anymore, since Go 1.15
But I still got the issue in Go 1.19. Concisely,
- I don't use runtime.Goshed()
- I used runtime.GOMAXPROCS(2)
If I put runtime.Ghoshed(), it work flawlessly. But without that, it seems Go executes a goroutine entirely before move to another.
Here is the code
func say(s string) {
for i := 0; i < 5; i++ {
fmt.Println(s)
}
}
func main() {
runtime.GOMAXPROCS(2)
go say("Hello")
say("World")
time.Sleep(time.Second)
}
Output (this seems cooperative, not preemptive )
Hello
Hello
Hello
Hello
Hello
World
World
World
World
World
Expected something like this
Hello
World
Hello
World
Hello
World
Hello
World
Hello
My CPU
fmt.Println(runtime.NumCPU())
Output: 12
We don't need to put runtime.Gosched() anymore. Your test gives you the illusion that one thread runs and then executes another thread. This is because your cpu runs faster. You can simply add a sleep, and the output of the test will be a normal concurrent output.