Home >Backend Development >Golang >How Does `runtime.Gosched()` Impact Go Program Execution Before and After Go 1.5?
In Go versions prior to 1.5, a piece of code involving runtime.Gosched() was observed to affect the output of a program:
func say(s string) { for i := 0; i < 5; i++ { runtime.Gosched() fmt.Println(s) } } func main() { go say("world") say("hello") }
Output with runtime.Gosched():
hello world hello world hello world hello world hello
Output without runtime.Gosched():
hello hello hello hello hello
In Go versions prior to 1.5, runtime.Gosched() explicitly yielded control to other goroutines when called. While Go programs run on a single OS thread by default, runtime.Gosched() allowed the scheduler to switch execution between goroutines.
When GOMAXPROCS was unset or set to 1, Go's cooperative multitasking required goroutines to explicitly yield control. Thus, in the code example above, the "world" output only appeared when runtime.Gosched() was called, as it allowed the scheduler to switch to the goroutine running the "world" print statement.
In Go 1.5 and later, runtime.GOMAXPROCS is set to the number of hardware cores by default, which means that Go may create multiple OS threads to run goroutines.
With GOMAXPROCS set to a value greater than 1, goroutines can run in parallel. However, unlike in preemptive multitasking systems, goroutines must still explicitly yield control to allow other goroutines to execute. This is because Go uses cooperative multitasking, where goroutines voluntarily surrender control to the scheduler.
With GOMAXPROCS set to a value greater than 1, the result of interleaving goroutines can become indeterministic, as the scheduler may switch execution between them at any time. This can lead to unpredictable output patterns, as seen in the example above when GOMAXPROCS was set to 2.
The above is the detailed content of How Does `runtime.Gosched()` Impact Go Program Execution Before and After Go 1.5?. For more information, please follow other related articles on the PHP Chinese website!