Explain preemption and fairness limitations
Explain preemption and fairness limitations
Preemption lets the runtime interrupt running work and schedule other goroutines. The implementation uses safe points and, on supported platforms, asynchronous preemption. It helps keep CPU-heavy code from monopolizing execution, but offers no strict FIFO, maximum wait or equal CPU share guarantee. runtime.Gosched voluntarily yields execution and the goroutine stays eligible to run; it is not synchronization or cancellation.
package main
import ( "fmt" "runtime")
func main() { old := runtime.GOMAXPROCS(1) defer runtime.GOMAXPROCS(old) c := make(chan int, 2) for i := 1; i <= 2; i++ { go func(n int) { runtime.Gosched(); c <- n }(i) } fmt.Println(<-c + <-c)}Gosched gives an opportunity to run something else, but no particular goroutine or order is promised. The channel collects both results. Removing Gosched preserves correctness; never fix a data race by adding yields.
Expected output:
3Use bounded work and explicit cancellation
package main
import ( "context" "errors" "fmt")
func process(ctx context.Context, n int) (int, error) { total := 0 for i := 0; i < n; i++ { if err := ctx.Err(); err != nil { return total, err } total += i } return total, nil}func main() { ctx, cancel := context.WithCancel(context.Background()) cancel() _, err := process(ctx, 100) fmt.Println(errors.Is(err, context.Canceled)) v, err := process(context.Background(), 4) fmt.Println(v, err == nil)}Preemption does not automatically terminate a canceled goroutine. Cooperative checks at bounded intervals let the function return. This small loop checks every iteration for clarity; measure overhead and responsiveness when choosing a chunk size. A context cannot forcibly interrupt an arbitrary blocking call.
Expected output:
true6 trueTry it locally
Create a worker that waits on either a canceled context or a job channel with no sender. Verify it exits with context.Canceled without using sleep.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime scheduler 05: Explain preemption and fairness limitations
Check the lesson objective before moving on.
What does Gosched guarantee?
How should CPU-heavy work respond to cancellation?