I'm learning golang. I have a goroutine to print variable i
and after it I write a deadloop. But when var i
up to 491519(or some other value)
, there is no output on the terminal. It looks like the goroutine which print var i
is no longer be scheduled, the CPU execute the deadloop all the way after output 491519
. Who can tell me the reason?
thanks.
My code:
package main
import (
"fmt"
"runtime"
)
func main() {
go func() {
i := 1
for {
fmt.Println(i)
i = i + 1
}
}()
runtime.GOMAXPROCS(4)
for {
}
}
I'd like to add that:
When I add fmt.Println("ABC")
in the last deadloop, the alternation of ABC
or i
output on the terminal forever.
my go version: go version go1.9.1 darwin/amd64
Goroutines are scheduled by Go runtime, therefore there are some limitations in comparison to the processes scheduling done by an operating system. An operating system can preempt processes by using timed interrupts, Go runtime cannot preempt goroutines.
Go runtime schedules another goroutine when goroutine
Setting GOMAXPROCS does not help much. Take a look at following program. It will use all processors and will stay in tight busy loops.
There are few ways of fixing your program:
Or
The work on improving the case of tight loops is ongoing.