Given following code:
package main
import (
"fmt"
"runtime"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
//runtime.Gosched()
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU()*2)
time.Sleep(100)
go f("i am not parallel")
go f("neither me")
var input string
fmt.Scanln(&input)
}
The output in most cases is:
i am not parallel : 0
i am not parallel : 1
i am not parallel : 2
neither me : 0
neither me : 1
neither me : 2
And sometimes:
neither me : 0
neither me : 1
neither me : 2
i am not parallel : 0
i am not parallel : 1
i am not parallel : 2
When runtime.Gosched()
is uncommented all seems to be OK.
I have tried changing GOMAXPROCS number from 2 to NumCPU, number of goroutines, cycles: none could get it to work in parallel.
Why so strange behaviour?
Edit: Ok, seems to be context-switching is heavy work and is not done very often without reasonable matters. One thing I still can't understand - why people get it to work without any sleep instructions?