Runtime Gosched Yields The Processor

Yield the processor between appends with runtime.Gosched under GOMAXPROCS(1), so two goroutines visibly alternate and the recorded order proves each handoff.

GoResilience

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"runtime"
	"sync"
)

func main() {
	// 单处理器下让出处理器,才能轮到别的 goroutine 推进
	runtime.GOMAXPROCS(1)
	var order []string
	var mu sync.Mutex
	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		for i := 0; i < 3; i++ {
			mu.Lock()
			order = append(order, "worker")
			mu.Unlock()
			// Gosched yields the processor so other goroutines can run
			runtime.Gosched()
		}
	}()

	for i := 0; i < 3; i++ {
		mu.Lock()
		order = append(order, "main")
		mu.Unlock()
		runtime.Gosched()
	}
	wg.Wait()
	fmt.Println(order)
}

Runtime Gosched Yields The Processor: inside the code

Runtime Gosched Yields The Processor reduces to the function main.

A single loop drives the file — for i := 0; i < 3; i++. A goroutine takes the work off the current one. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Caveats

  • Self-contained: imports go no further than the runtime’s own modules.

Using it

Signature: func main()

Key statements

order = append(order, "worker")
order = append(order, "main")
var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

How do you run Runtime Gosched Yields The Processor?
This is a complete program, not a library excerpt — execution starts at the top.