Home >Backend Development >Golang >How Does `runtime.Gosched()` Impact Go Program Execution Before and After Go 1.5?

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

Susan Sarandon
Susan SarandonOriginal
2024-12-30 14:37:16770browse

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 < 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

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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn