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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How do you run Runtime Gosched Yields The Processor?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.