liveBook · Manning

Runtime.Gosched

As explained in Learn Concurrent Programming with Go

runtime.Gosched is a Go runtime function that yields the processor so the scheduler can select another runnable goroutine.

runtime.Gosched yields the processor so another runnable goroutine can run. It invokes the Go scheduler from the current goroutine, but does not suspend it permanently. section 2.3.3 section 3.3.2

Use runtime.Gosched with these limitations in mind:

  • Calling it gives another goroutine a chance to execute before the current goroutine continues. section 2.3.3
  • It provides no guarantee about which goroutine the scheduler selects or whether another goroutine runs at all. section 2.3.3
  • It does not make unsynchronized shared-memory updates safe and must not be used to fix race conditions. section 3.3.2

Giving a greeting goroutine a chance

Starting sayHello in a goroutine and then calling runtime.Gosched before printing Finished increases the chance that Hello appears. The program can still finish without printing Hello because main may continue or terminate first. section 2.3.3

Listing 2.5 Calling the Go scheduler
package main

import (
    "fmt"
    "runtime"
)

func sayHello() {
    fmt.Println("Hello")
}

func main() {
    go sayHello()
    runtime.Gosched()        #1
    fmt.Println("Finished")
}
#1 Calling the Go scheduler gives the other goroutine a chance to run.

Runnable listing showing runtime.Gosched called after starting sayHello. section 2.3.3

How Learn Concurrent Programming with Go covers it

How deep it goes
Defines yielding and its nondeterminism, then demonstrates scheduling effects without providing synchronization guarantees.
Examples
Demonstrates sayHello versus Finished output and shared-money updates from stingy and spendy goroutines.
What it assumes
Assumes goroutines and shared variables, while defining processor yielding and scheduler selection through small examples.
What you can do after
Apply runtime.Gosched to offer scheduling opportunities while recognizing that it cannot control execution order or prevent races.
How it connects
Connects goroutines, the Go scheduler, context switching, shared memory, and race conditions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.