go - Goroutines don't work in parallel -
given following code:
package main import ( "fmt" "runtime" "time" ) func f(from string) { := 0; < 3; i++ { fmt.println(from, ":", i) //runtime.gosched() } } func main() { runtime.gomaxprocs(runtime.numcpu()*2) time.sleep(100) go f("i not parallel") go f("neither me") var input string fmt.scanln(&input) }
the output in cases is:
i not parallel : 0
not parallel : 1
not parallel : 2
neither me : 0
neither me : 1
neither me : 2
and sometimes:
neither me : 0
neither me : 1
neither me : 2
not parallel : 0
not parallel : 1
not parallel : 2
when runtime.gosched()
uncommented seems ok. have tried changing gomaxprocs number 2 numcpu, number of goroutines, cycles: none work in parallel.
why strange behaviour?
edit: ok, seems context-switching heavy work , not done without reasonable matters. 1 thing still can't understand - why people get work without sleep instructions?
you should not predict goroutine schedule. running example provided, got output.
direct : 0 direct : 1 direct : 2 goroutine : 0 goroutine : 1 goroutine : 2 going done
if add runtime.gomaxprocs(4)
@ begin of main function, , run on i5 qcore desktop ubuntu, output
direct : 0 direct : 1 direct : 2 goroutine : 0 goroutine : 1 goroutine : 2 going done
it not produce same output think. should assume goroutine may parallel, add lock if need control sequence.
Comments
Post a Comment