CodeBlanks Logo Icon CodeBlanks

Work stealing

Learn the work-stealing mechanism of idle processors.

Work stealing

Each P has a local queue with 256 slots; there is also a global queue shared by all Ps. When a P runs out of work it checks, in order: its own queue → the global queue → the network poller → stealing half of another P's queue.

P0: [G1 G2 G3 G4]   P1: []
P1 steals →  P0: [G1 G2]  P1: [G3 G4]

This balances load across cores without a central lock.

runnext and locality

A newly created goroutine is placed in the creating P's runnext slot and becomes the next to run. In producer–consumer patterns the two goroutines run back-to-back on the same P, keeping caches warm. If the local queue overflows, half of it moves to the global queue.

Practice Parallel workers

Start 8 goroutines with a sync.WaitGroup; each sums 1 to 1000 and writes the result into a slice at its own index. Wait for all of them and print the first value in the slice.

Starter code

main.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    sonuc := make([]int, 8)
    var wg sync.WaitGroup
    for i := 0; i < 8; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            t := 0
            for j := 1; j <= 1000; j++ {
                t += j
            }
            sonuc[i] = t
        }(i)
    }
    wg.Wait()
    fmt.Println(sonuc[0])
}

Expected output

500500

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is the global queue sometimes checked before the local one?

  • Because it's faster
  • Because the local queue can't be empty
  • Because the GC requires it
  • So goroutines in the global queue don't starve Correct answer

Explanation: Every 61 scheduling ticks the scheduler checks the global queue; otherwise busy local queues could keep global work waiting forever.

2 Amount stolen

Question
calinan := len(kurban.kuyruk) / ____
Answer
calinan := len(kurban.kuyruk) / 2

Explanation: Stealing half quickly balances work between two Ps.

3 Queue and feature

Term Meaning
Yerel kuyruk Per P, 256 slots
Global kuyruk Shared, locked
runnext The next G to run
Work stealing Taking work from another P

All lessons in Expert