System Design

G10

The runtime and scheduler

The runtime multiplexes goroutines onto threads and frees memory while your code runs. Here is how the scheduler moves work, and how GOGC and GOMAXPROCS change what you measure.

Not startedSaved in this browser only.
  1. 1A goroutine runs on a thread only while that thread holds a P. GOMAXPROCS is the number of Ps.
  2. 2An idle P steals half of another P's queue. The scheduler keeps every P busy without a central lock on the fast path.
  3. 3GC work scales with live data, and frequency scales with allocation. GOGC trades memory for CPU.
  4. 4Set GOMEMLIMIT to protect a container. Since Go 1.25, GOMAXPROCS follows the cgroup CPU limit.
G10
    A

    The trap

    recorded on 20 runs
    a loop with no function callgo
    // GOMAXPROCS is 1. One goroutine spins in a loop with no function call, and
    // main sleeps for 10 ms. Who finishes first? The program runs itself twice:
    // once with defaults, and once with asynchronous preemption turned off.
    package main
    
    import (
      "fmt"
      "os"
      "os/exec"
      "runtime"
      "sync/atomic"
      "time"
    )
    
    var sink int
    
    func spin() {
      total := 0
      for i := range 2_000_000_000 {
        total += i2
      }
      sink = total
    }
    
    func race() string {
      runtime.GOMAXPROCS(1)1
      start := time.Now()
      var running atomic.Bool
      go func() {
        running.Store(true)
        spin()
      }()
      for !running.Load()3 {
        runtime.Gosched()
      }
      time.Sleep(10 * time.Millisecond)4
      if time.Since(start) > 200*time.Millisecond {
        return "main woke late: it waited for the loop"
      }
      return "main woke on time: the runtime stopped the loop"
    }
    
    func main() {
      if os.Getenv("CHILD") != "" {
        fmt.Println(race())
        return
      }
      for _, debug := range []string{"", "asyncpreemptoff=1"} {
        cmd := exec.Command(os.Args[0])
        cmd.Env = append(os.Environ(), "CHILD=1", "GODEBUG="+debug)
        out, err := cmd.Output()
        if err != nil {
          fmt.Println(err)
          os.Exit(1)
        }
        fmt.Printf("GODEBUG=%q: %s", debug, out)
      }
    }
    1. 1One P, so one goroutine runs Go code at a time.
    2. 2No call in this loop, so no stack check, so no cooperative stop point.
    3. 3Main gives way until the loop has started. Time counts from before this wait.
    4. 4Main needs a P to wake. Only the spinner has it.
    settingrecorded outputstatus
    defaultmain woke on time: the runtime stopped the loopPreempted
    asyncpreemptoff=1main woke late: it waited for the loopAs before Go 1.14
    • The sysmon thread sees that a goroutine has held its P for 10 ms.
    • It sends SIGURG to the thread. The signal handler stops the goroutine at a safe instruction.
    • The same stop is what lets a garbage collection begin during a tight loop.
    • Programs that make raw system calls can now see EINTR. Retry those calls.

    Since Go 1.14, a tight loop cannot hold a P forever. The runtime preempts it with a signal after about 10 ms.

    B

    The model: G, M and P

    runtime/proc.go, Go 1.27
    thread M0P0G1runningG2runnextG3G4G5local queue, up to 256thread M1P1G6runningrunnextG7local queue, up to 256thread M2P2G8runningrunnextlocal queue, up to 256a P with no work steals halfglobal queueread on every 61st tick, and when a P runs drysysmona thread with no P
    what it ishow many
    GStack, state and the function to run.Millions
    MAn OS thread.Limit 10,000; change it with debug.SetMaxThreads
    PA run queue and the allocator caches.GOMAXPROCS
    • A P runs runnext, then its local queue, then the global queue. Then it steals.
    • A blocked goroutine parks. It holds no M and no P.

    G is the goroutine, M is the thread, P is the right to run Go code. Threads can outnumber Ps, because a thread in a system call does not need a P.

    C

    See it: the scheduler, step by step

    a model that follows runtime/proc.go; the local queue holds 4 here and 256 in the runtime
    P0thread M0runningG1runnextlocal queueP1no threadrunningrunnextlocal queueglobal queueemptyparkednonein syscallnoneidle threadsnone

    step 1 of 16, runtime: schedinit

    The program starts

    G1 runs on P0. Thread M0 holds P0. P1 is idle and has no thread.

    Solid goroutines moved in this step.

    A test replays each step and proves that no goroutine is lost or doubled. The execution tracer confirms that real goroutines move between Ps (panel N).

    New work goes to runnext. Overflow goes global. Idle Ps steal half. sysmon takes back a P from a thread stuck in the kernel.

    D

    The rules: what blocks what

    recorded with /sched/threads/total:threads
    100 goroutines inrecordedstatus
    time.Sleepunder 50 threads: trueParks
    conn.Readunder 50 threads: trueParks in the netpoller
    syscall.Readat least 100 threads: trueEach holds a thread
    a cgo callA thread for the callSame as a system call
    • On a system call, the thread keeps its P at first. sysmon retakes the P after at least 20 µs if other work waits.
    • Sockets use the netpoller, so one thread can serve many waits.
    • On return, a goroutine takes an idle P, or goes to the global queue.

    A goroutine that waits in the runtime costs a stack. A goroutine in a blocking system call also costs a thread.

    E

    The rules: preemption

    runtime/proc.go, and Go 1.14 notes
    situationresult
    Goroutine runs for 10 mssysmon marks it. It stops at its next function entry.
    Goroutine has no callsA signal stops it. Since Go 1.14.
    Preempted goroutineGoes to the global queue.
    Goroutine parks or calls GoschedGives up the P at once.
    runnext goroutinesShare one time slice, so two goroutines cannot starve the rest.
    Stop the worldPreempts every P. Latency here is the time to reach each one.

    Do not add runtime.Gosched to a loop to be fair. The runtime handles that.

    Preemption has two paths: a check at function entry, and a signal for code with no calls.

    F

    Stacks: grow by copying

    recorded
    the stack moves under a pointergo
    // A local variable stays on the stack, and the stack grows while p points at
    // it. Does the pointer survive?
    package main
    
    import (
      "fmt"
      "unsafe"
    )
    
    func deep(n int) int {1
      var pad [256]byte
      pad[n%256] = 1
      if n == 0 {
        return int(pad[0])
      }
      return deep(n-1) + int(pad[n%256])
    }
    
    func main() {
      done := make(chan struct{})
      go func() {
        defer close(done)
        x := 42
        p := &x
        before := uintptr(unsafe.Pointer(p))
        deep(10_000)
        after := uintptr(unsafe.Pointer(p))
        fmt.Println("address changed:", before != after2)
        fmt.Println("p still points at x:", p == &x3, *p)
      }()
      <-done
    }
    1. 1Each function checks the stack bound at entry. A failed check calls the runtime, which grows the stack.
    2. 2The stack is now at a new address.
    3. 3The runtime rewrote p during the copy. This needs precise stack maps, in place since Go 1.3.

    Recorded output: address changed: true; p still points at x: true 42

    A stack starts at about 2 KB and doubles by copying. The runtime fixes pointers into the stack, so my code cannot see the move.

    G

    The rules: stacks

    runtime/stack.go and release notes
    questionanswer
    Start size2,048 B here. Since Go 1.19 it follows the average use of the program.
    GrowthDoubles, then copies. Contiguous since Go 1.3.
    ShrinkDuring GC, to half, if the goroutine uses under a quarter.
    Limit1 GB on 64-bit systems. debug.SetMaxStack changes it.
    At the limit"fatal error: stack overflow". Recover cannot catch it.
    Why not a large fixed stackA million goroutines would reserve too much address space and memory.

    Deep recursion costs a copy at each doubling, and the amortized cost is small. Stack overflow is fatal, and recover cannot stop it.

    H

    The collector: one cycle

    runtime/mgc.go, Go 1.27
    sweepconcurrentSTWmark and scanconcurrent, about 25% of GOMAXPROCSSTWsweepconcurrent, on allocationsweep term.mark term.write barrier ongoroutines run, except in the two STW pausesA goroutine that allocates fast during mark does a share of the marking itself. That is a mark assist.
    • Mark starts from the roots: goroutine stacks and globals. It follows every pointer in the heap.
    • The write barrier records pointer writes during mark, so a moved pointer cannot hide a live object.
    • Go uses a hybrid barrier: a Yuasa deletion barrier with a Dijkstra insertion barrier. Stacks need no rescan.
    • The target for background mark is 25% of GOMAXPROCS. Idle Ps can also help.
    • Go does not move objects and has no generations. Sweep frees unmarked memory as allocation needs it.

    The collector marks concurrently with a write barrier on. It stops the world twice, briefly, and those pauses do not grow with the heap.

    I

    Green Tea

    the default since Go 1.26
    beforeGreen Tea
    Work list holdsObjectsWhole pages
    Queue orderA stackFirst in, first out
    LocalityJumps around memoryScans nearby objects together
    Scale with coresA shared queue contendsSmaller queues contend less
    GC CPU here, GOGC 1003.4 s2.1 s
    • On this workload, Green Tea used 39% less GC CPU. Results vary by program. Small objects with many pointers gain most.
    • Newer amd64 CPUs gain about 10% more from vector instructions.
    • GOEXPERIMENT=nogreenteagc still builds the old collector in Go 1.27.3. The 1.26 notes expected that to end in 1.27.

    Green Tea scans pages and not single objects. The release notes expect 10 to 40% less GC cost, and it needs no change to your code.

    J

    What GOGC does

    the GC guide; goal checked against measured runs
    GOGClivegoalgoal / live
    25148 MiB185 MiB1.25
    50160 MiB240 MiB1.50
    100172 MiB344 MiB2.00
    200179 MiB538 MiB3.00
    400172 MiB861 MiB5.00

    Target heap = live heap + (live heap + GC roots) × GOGC / 100. Roots count since Go 1.18. They are small in this program. The minimum total heap target is 4 MiB × GOGC / 100.

    The next cycle starts when the heap reaches live plus live times GOGC over 100. Doubling GOGC halves the GC work and doubles the headroom.

    K

    See it: GOGC on a fixed workload

    runtime/metrics, median of 3 runs
    Peak heapGOGC 25186 MiBGOGC 50243 MiBGOGC 100333 MiBGOGC 200461 MiBGOGC 400752 MiB
    GC CPU, all threadsGOGC 257.9 sGOGC 503.8 sGOGC 1002.1 sGOGC 2001.1 sGOGC 4000.5 s
    GOGCcyclespeak heapGC CPUwall timepause p50pause p99
    25112186 MiB7.9 s1.3 s66 µs164 µs
    5053243 MiB3.8 s0.8 s49 µs164 µs
    10028333 MiB2.1 s0.6 s66 µs164 µs
    20015461 MiB1.1 s0.5 s66 µs131 µs
    4007752 MiB0.5 s0.5 s57 µs115 µs

    128 MiB live, in a tree of 128-byte nodes, with 4 GiB of churn from 4 goroutines. The test asserts that cycles and GC CPU fall and peak heap rises at each step. Pause numbers vary by run and are not asserted. Each pause is a bucket bound of the histogram.

    GOGC trades memory for CPU. Pauses stay near or under 1 ms at every value, so I tune it for cost and not for latency.

    L

    GOMEMLIMIT

    the GC guide, and one measured run
    caseuse it
    A container with a fixed limit: leave 5 to 10% headroomApproved
    GOGC=off with a limit, in a dedicated containerMost heap, least GC
    Shared memory with other programsKeep a GOGC too
    A CLI tool, or memory that grows with inputNot approved
    A program already near its limitSlow, not safe

    Measured: GOGC=off and GOMEMLIMIT=256MiB peaked at 236 MiB of heap, with 58 cycles. The limit covers all runtime memory, not only the heap. The GC CPU limit is roughly 50%.

    In a container, I set GOMEMLIMIT to about 90% of the limit. It is a soft limit, and the GC stops at about 50% CPU rather than thrash.

    M

    Read a gctrace line

    recorded with GODEBUG=gctrace=1
    one cyclestderr
    gc 32 @0.719s 7%:4 0.062+7.9+0.057 ms clock1,
      1.0+1.0/27/41+0.91 ms cpu2, 294->333->174 MB, 345 MB goal3,
      0 MB stacks, 0 MB globals, 16 P
    1. 1Wall time: sweep termination, concurrent mark, mark termination. The first and third are the pauses.
    2. 2CPU time. The middle term splits into assist, background and idle mark.
    3. 3The heap size at which this cycle aimed to finish.
    4. 4Share of time in GC since the program started.

    The runtime package documents this format. The format can change between releases.

    The three clock numbers are pause, concurrent mark, pause. The MB triple is heap at start, at end, and live.

    N

    See it: latency against GOMAXPROCS

    runtime/metrics and the execution tracer, median of 3 runs
    Scheduling latency, p99 (log scale)1 P67.1 ms2 P41.9 ms4 P14.7 ms8 P3.1 ms16 P393 µs
    GOMAXPROCSwall timePs usedmoves between Psof resumes
    10.86 s101,503
    20.44 s23141,504
    40.23 s48501,991
    80.14 s82,2203,320
    160.09 s167,2938,225

    32 goroutines wake at one gate, 400 times, and each does a short burst of CPU work. The test asserts that p99 latency and wall time fall from 1 to 4 to 16 Ps. The last three columns come from an execution trace. Moves count a goroutine that resumed on a different P.

    Scheduling latency is the time a runnable goroutine waits for a P. If it grows, I have too few Ps for the runnable work.

    O

    GOMAXPROCS in a container

    Go 1.25 release notes
    settingresult
    Default, on Linux, with a CPU limitThe lower of logical CPUs and the cgroup limit.
    Limit or CPU count changesThe runtime updates GOMAXPROCS, on all systems.
    CPU request with no limitIgnored.
    GOMAXPROCS variable or a manual callBoth behaviours turn off.
    containermaxprocs=0, updatemaxprocs=0Turn each one off by GODEBUG.
    runtime.SetDefaultGOMAXPROCSReturns to the default.

    Before Go 1.25, a container with a low CPU limit on a large host got too many Ps, and the kernel throttled it. The new default needs a go directive of 1.25 or later.

    Since Go 1.25, GOMAXPROCS follows the cgroup CPU limit on Linux and updates at run time. CPU requests do not count, only limits.

    P

    Read runtime/metrics

    the code that made these numbers
    read named samplesgo
    s := []metrics.Sample{
      {Name: "/gc/cycles/total:gc-cycles"},
      {Name: "/cpu/classes/gc/total:cpu-seconds"},
      {Name: "/cpu/classes/user:cpu-seconds"},
      {Name: "/sched/pauses/total/gc:seconds"1},
      {Name: "/gc/heap/goal:bytes"},
      {Name: "/gc/heap/live:bytes"},
      {Name: "/gc/stack/starting-size:bytes"},
    }
    metrics.Read(s)2
    pauses := s[3].Value.Float64Histogram()
    1. 1A histogram of stop-the-world time for GC.
    2. 2Reuse the slice. Read fills each sample, with no stop of the world.
    a quantile from a histogramgo
    // quantile reads a fraction from a runtime/metrics histogram. It returns the
    // upper bound of the bucket that holds it.
    func quantile(h *metrics.Float64Histogram, q float64) float64 {
      var total uint64
      for _, c := range h.Counts {
        total += c
      }
      want := uint64(q * float64(total))
      var seen uint64
      for i, c := range h.Counts {
        seen += c
        if c > 0 && seen >= want {
          return h.Buckets[i+1]1
        }
      }
      return 0
    }
    1. 1Buckets has one more entry than Counts. A bucket gives a bound, not an exact value.

    runtime/metrics is the stable way to read the runtime. Each sample has a name with a unit, and latency comes as a histogram.

    Q

    Take an execution trace

    the code that made the table in panel N
    write a tracego
    if path := os.Getenv("TRACE"); path != "" {
      f, err := os.Create(path)
      if err != nil {
        fatal(fmt.Errorf("create trace: %w", err))
      }
      defer f.Close()
      if err := trace.Start(f)1; err != nil {
        fatal(fmt.Errorf("start trace: %w", err))
      }
      defer trace.Stop()
    }
    1. 1Since Go 1.21 this costs much less CPU, up to 10 times less than before on amd64 and arm64.
    questiontool
    Where does CPU go?pprof CPU profile
    Why did this request stall?go tool trace
    A rare slow event in productiontrace.FlightRecorder
    Too few Ps?/sched/latencies:seconds
    GC pauses?/sched/pauses/total/gc:seconds

    pprof says where the CPU goes. The tracer says when goroutines waited. For a rare event, I use a flight recorder.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.3Contiguous stacks replace segmented stacks. Stack values are precise.Stacks grow by copying.
    1.5A concurrent collector. GOMAXPROCS defaults to the number of cores.Pauses fall to under 10 ms.
    1.8No stop-the-world stack rescan.Pauses usually under 100 µs.
    1.14Asynchronous preemption.A tight loop cannot hold a P.
    1.18GOGC counts GC roots.The heap goal includes stacks and globals.
    1.19GOMEMLIMIT. Start stack size follows average use. GC CPU limit of 50%.A real memory budget for containers.
    1.21GC tuning cuts tail latency by up to 40%. Traces cost far less.Keep a tracer on in more places.
    1.24Swiss Table maps. A new runtime mutex. runtime.AddCleanup. Package weak.2 to 3% less CPU on average.
    1.25Container-aware GOMAXPROCS. SetDefaultGOMAXPROCS. trace.FlightRecorder. Green Tea as an experiment.Container CPU limits work with no extra library.
    1.26Green Tea is the default. Scheduler metrics under /sched/goroutines. Heap base address is randomized. cgo calls cost about 30% less.Count goroutines by state with runtime/metrics.
    1.27Size-specialized allocation for objects under 80 bytes. Stack dumps print pprof labels.Small allocations cost up to 30% less, about 1% in real programs.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildYou want a goroutine per request.That is the model. A parked goroutine costs a stack, and net/http does this for you.
    buildWork is CPU-bound.Size the pool near GOMAXPROCS. More goroutines only add latency. See G12.
    talk"How many goroutines can you run?"Memory sets the limit, at about 3 KB each. Threads stay near GOMAXPROCS, except during blocking system calls.
    talk"p99 rose after a deploy."Read /sched/latencies:seconds and the GC pause histogram. Then take a trace of one slow request.
    talk"The pod is OOM-killed."Set GOMEMLIMIT with 5 to 10% headroom. Then find what grows with a heap profile.
    talk"Why not pool everything?"GC cost follows live pointers. Pool hot buffers only, and measure.
    talk"How does Go compare with a thread per request?"Go parks a goroutine in user space, and sockets share the netpoller. So a wait holds no thread.

    I keep the live heap small and let GOGC stay at 100 until a profile says otherwise.

    T

    Drill

    each answer is the output of a real run

    0 of 8 known

    1. Predict the output. GOMAXPROCS is 1.

      package main
      
      import (
        "fmt"
        "runtime"
        "strings"
        "sync"
      )
      
      func main() {
        runtime.GOMAXPROCS(1)
        var mu sync.Mutex
        var out strings.Builder
        var wg sync.WaitGroup
        for i := range 5 {
          wg.Go(func() {
            mu.Lock()
            defer mu.Unlock()
            fmt.Fprint(&out, i, " ")
          })
        }
        wg.Wait()
        fmt.Println(out.String())
      }
    2. Predict the output.

      // 10,000 goroutines wait on one channel. How many threads does that take?
      package main
      
      import (
        "fmt"
        "runtime"
        "runtime/metrics"
        "time"
      )
      
      func main() {
        gate := make(chan struct{})
        for range 10_000 {
          go func() { <-gate }()
        }
        time.Sleep(50 * time.Millisecond)
        s := []metrics.Sample{{Name: "/sched/threads/total:threads"}}
        metrics.Read(s)
        fmt.Println("goroutines:", runtime.NumGoroutine())
        fmt.Println("under 50 threads:", s[0].Value.Uint64() < 50)
        close(gate)
      }
    3. Predict the output. GOMAXPROCS is 1, and the spin takes about 1 s.

      // GOMAXPROCS is 1. One goroutine spins in a loop with no function call, and
      // main sleeps for 10 ms. Who finishes first? The program runs itself twice:
      // once with defaults, and once with asynchronous preemption turned off.
      package main
      
      import (
        "fmt"
        "os"
        "os/exec"
        "runtime"
        "sync/atomic"
        "time"
      )
      
      var sink int
      
      func spin() {
        total := 0
        for i := range 2_000_000_000 {
          total += i
        }
        sink = total
      }
      
      func race() string {
        runtime.GOMAXPROCS(1)
        start := time.Now()
        var running atomic.Bool
        go func() {
          running.Store(true)
          spin()
        }()
        for !running.Load() {
          runtime.Gosched()
        }
        time.Sleep(10 * time.Millisecond)
        if time.Since(start) > 200*time.Millisecond {
          return "main woke late: it waited for the loop"
        }
        return "main woke on time: the runtime stopped the loop"
      }
      
      func main() {
        if os.Getenv("CHILD") != "" {
          fmt.Println(race())
          return
        }
        for _, debug := range []string{"", "asyncpreemptoff=1"} {
          cmd := exec.Command(os.Args[0])
          cmd.Env = append(os.Environ(), "CHILD=1", "GODEBUG="+debug)
          out, err := cmd.Output()
          if err != nil {
            fmt.Println(err)
            os.Exit(1)
          }
          fmt.Printf("GODEBUG=%q: %s", debug, out)
        }
      }
    4. Predict the output. deep calls itself 10,000 times.

      // A local variable stays on the stack, and the stack grows while p points at
      // it. Does the pointer survive?
      package main
      
      import (
        "fmt"
        "unsafe"
      )
      
      func deep(n int) int {
        var pad [256]byte
        pad[n%256] = 1
        if n == 0 {
          return int(pad[0])
        }
        return deep(n-1) + int(pad[n%256])
      }
      
      func main() {
        done := make(chan struct{})
        go func() {
          defer close(done)
          x := 42
          p := &x
          before := uintptr(unsafe.Pointer(p))
          deep(10_000)
          after := uintptr(unsafe.Pointer(p))
          fmt.Println("address changed:", before != after)
          fmt.Println("p still points at x:", p == &x, *p)
        }()
        <-done
      }
    5. Predict the output. The limit is 1 MiB.

      // Recursion with no base case, with the stack limit set to 1 MiB. The child
      // run prints addresses, so the parent keeps only the lines that do not.
      package main
      
      import (
        "bufio"
        "bytes"
        "fmt"
        "os"
        "os/exec"
        "runtime/debug"
        "strings"
      )
      
      func recurse(n int) int { return recurse(n+1) + 1 }
      
      func main() {
        if os.Getenv("CHILD") != "" {
          debug.SetMaxStack(1 << 20)
          fmt.Println(recurse(0))
          return
        }
        cmd := exec.Command(os.Args[0])
        cmd.Env = append(os.Environ(), "CHILD=1")
        var out bytes.Buffer
        cmd.Stderr = &out
        err := cmd.Run()
        scan := bufio.NewScanner(&out)
        for scan.Scan() {
          line := scan.Text()
          fatal := strings.HasPrefix(line, "fatal error")
          if fatal || strings.Contains(line, "exceeds") {
            fmt.Println(line)
          }
        }
        fmt.Println("exit:", err)
      }
    6. Predict the output.

      // 100 goroutines block in three ways. How many OS threads does each take?
      package main
      
      import (
        "fmt"
        "net"
        "os"
        "runtime/metrics"
        "sync"
        "syscall"
        "time"
      )
      
      func threads() int {
        s := []metrics.Sample{{Name: "/sched/threads/total:threads"}}
        metrics.Read(s)
        return int(s[0].Value.Uint64())
      }
      
      // during starts 100 goroutines and returns the thread count while they block.
      func during(block func()) int {
        var wg sync.WaitGroup
        for range 100 {
          wg.Go(block)
        }
        time.Sleep(50 * time.Millisecond)
        n := threads()
        wg.Wait()
        return n
      }
      
      func fatal(err error) {
        fmt.Println(err)
        os.Exit(1)
      }
      
      func main() {
        slept := during(func() { time.Sleep(100 * time.Millisecond) })
      
        ln, err := net.Listen("tcp", "127.0.0.1:0")
        if err != nil {
          fatal(err)
        }
        defer ln.Close()
        polled := during(func() {
          c, err := net.Dial("tcp", ln.Addr().String())
          if err != nil {
            fatal(err)
          }
          defer c.Close()
          c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
          c.Read(make([]byte, 1))
        })
      
        syscalled := during(func() {
          fds := make([]int, 2)
          if err := syscall.Pipe(fds); err != nil {
            fatal(err)
          }
          defer syscall.Close(fds[0])
          defer syscall.Close(fds[1])
          time.AfterFunc(100*time.Millisecond, func() {
            syscall.Write(fds[1], []byte{1})
          })
          syscall.Read(fds[0], make([]byte, 1))
        })
      
        fmt.Println("100 in time.Sleep, under 50 threads:", slept < 50)
        fmt.Println("100 in a socket read, under 50 threads:", polled < 50)
        fmt.Println("100 in a raw blocking read, at least 100 threads:",
          syscalled >= 100)
      }
    7. Predict the output.

      package main
      
      import (
        "fmt"
        "runtime"
        "runtime/debug"
      )
      
      var sink []byte
      
      func cycles(alloc func()) uint32 {
        var before, after runtime.MemStats
        runtime.ReadMemStats(&before)
        alloc()
        runtime.ReadMemStats(&after)
        return after.NumGC - before.NumGC
      }
      
      func churn() {
        for range 2000 {
          sink = make([]byte, 1<<20)
        }
      }
      
      func main() {
        debug.SetGCPercent(-1)
        fmt.Println("GOGC off, 2 GiB allocated, cycles:", cycles(churn))
        debug.SetMemoryLimit(128 << 20)
        fmt.Println("then a 128 MiB limit, cycles > 0:", cycles(churn) > 0)
      }
    8. Predict the output.

      package main
      
      import (
        "fmt"
        "runtime"
      )
      
      func main() {
        start := runtime.GOMAXPROCS(0)
        runtime.GOMAXPROCS(2)
        fmt.Println("after GOMAXPROCS(2):", runtime.GOMAXPROCS(0))
        runtime.SetDefaultGOMAXPROCS()
        fmt.Println("default restored:", runtime.GOMAXPROCS(0) == start)
      }
    U

    Numbers to say

    source and runtime/metrics
    time slice
    10 ms, then sysmon preempts.
    local queue
    256 goroutines. Steal takes half.
    global check
    Every 61st tick.
    start stack
    2,048 B; limit 1 GB.
    GC pause
    p99 of 164 µs at GOGC 100, measured.
    GC goal
    2.0 times the live heap at GOGC 100.
    GOGC 25 to 400
    186 MiB to 752 MiB of heap; 7.9 s to 0.5 s of GC CPU.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16 unless set, on a busy machine. The first three rows come from the runtime source. Use the others as orders of magnitude.