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; iOutput with runtime.Gosched():
hello world hello world hello world hello world helloOutput without runtime.Gosched():
hello hello hello hello helloExplanation
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.
GOMAXPROCS and Cooperative Multitasking
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.
Implications for Parallelism
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3