"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The impact of `runtime.Gosched()` before and after Go 1.5 on Go program execution

The impact of `runtime.Gosched()` before and after Go 1.5 on Go program execution

Posted on 2025-04-14
Browse:176

How Does `runtime.Gosched()` Impact Go Program Execution Before and After Go 1.5?

How Gosched Affects the Execution of Go Programs

Problem

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 

Output with runtime.Gosched():

hello
world
hello
world
hello
world
hello
world
hello

Output without runtime.Gosched():

hello
hello
hello
hello
hello

Explanation

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.

Latest tutorial More>

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