Skip to content
Huseyin Babal
Go back

Go scheduler: how a million goroutines fit on five threads

I started one million goroutines that all block on the same channel, then asked the runtime how many operating system threads it had created for them. On a 4-vCPU Linux VM with Go 1.27.3 the answer was five.

$ go run million.go
goroutines: 1000001
OS threads: 5
CPU cores:  4
stacks:     1953 MB
started in: 586ms

This post walks through why that works: what a goroutine costs, how the scheduler maps goroutines onto threads, how it keeps four cores busy, how it takes the CPU back from a goroutine that never yields, and the one situation where the thread count does follow the goroutine count.

Setup

Every number here comes from one Linux VM: 4 vCPUs, arm64, Go 1.27.3, ulimit -s 8192. The programs are short and standard-library only; each section shows the one you need. Thread counts come from pprof.Lookup("threadcreate").Count(), which reports how many OS threads the runtime has created.

The program behind the output above:

package main

import (
	"fmt"
	"runtime"
	"runtime/pprof"
	"time"
)

func main() {
	start := time.Now()
	done := make(chan struct{})
	const n = 1_000_000
	for i := 0; i < n; i++ {
		go func() { <-done }()
	}
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("goroutines: %d\n", runtime.NumGoroutine())
	fmt.Printf("OS threads: %d\n", pprof.Lookup("threadcreate").Count())
	fmt.Printf("CPU cores:  %d\n", runtime.NumCPU())
	fmt.Printf("stacks:     %d MB\n", m.StackSys/1024/1024)
	fmt.Printf("started in: %v\n", time.Since(start).Round(time.Millisecond))
	close(done)
}

The count is 1,000,001 because main is a goroutine too. Over five runs the start-up time was 881, 554, 556, 545 and 570 ms; the thread count was 5 every time.

What a goroutine costs

A thread created with default settings on this machine gets an 8 MB stack reservation (ulimit -s 8192). A goroutine starts with a 2 KB stack that the runtime grows and shrinks as needed. Two kilobytes times a million is about 2 GB, which is the StackSys value in the output: 1953 MB.

To see where the 586 ms of start-up goes, wrap the loop in a CPU profile:

f, _ := os.Create("million.prof")
pprof.StartCPUProfile(f)
for i := 0; i < 1_000_000; i++ {
	go func() { <-done }()
}
pprof.StopCPUProfile()
$ go tool pprof -top -nodecount=5 million.prof
Duration: 682.76ms, Total samples = 1660ms (243.13%)
      flat  flat%   sum%        cum   cum%
     270ms 16.27% 16.27%      270ms 16.27%  runtime.stackpoolalloc
      90ms  5.42% 21.69%       90ms  5.42%  runtime.futex
      80ms  4.82% 26.51%      350ms 21.08%  runtime.chanrecv
      70ms  4.22% 30.72%       70ms  4.22%  runtime.memclrNoHeapPointers
      60ms  3.61% 34.34%       60ms  3.61%  runtime.nanotime (inline)

runtime.stackpoolalloc hands out the small fixed-size stacks and is the biggest single function. In the flame graph (go tool pprof -http=:8080 million.prof), every go statement goes through runtime.newproc1 (27.71% cumulative), which calls runtime.malg to build the goroutine and its stack (24.10% cumulative), with stackpoolalloc at the bottom of that tower. Creating a goroutine is mostly allocating a stack, and a small one at that.

G, M and P

The runtime’s scheduler is built from three structures, defined in runtime/runtime2.go:

What it is
Ga goroutine: its stack, its program counter, its state
Ma machine, i.e. an OS thread
Pa processor: a slot that an M must hold to run Go code, with its own run queue

The number of Ps is GOMAXPROCS, which defaults to the number of CPUs the process may use (4 here). Go code only runs on an M that holds a P, so on this VM no more than four goroutines are executing at the same moment, whether there are ten or a million. The other Ms in the count are threads the runtime keeps for its own work, such as sysmon (below), or idle threads it parked earlier.

Parked goroutines cost no thread at all. The million goroutines blocked on <-done are just G structures on the channel’s wait list. No M is waiting on their behalf.

To see the limit on running goroutines, give the scheduler more CPU work than cores:

func work() {
	x := 0
	for i := 0; i < 300_000_000; i++ {
		x += i
	}
	_ = x
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 300; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); work() }()
	}
	wg.Wait()
}
$ go tool pprof -top -nodecount=2 queues.prof
Duration: 5.72s, Total samples = 22.92s (400.67%)
      flat  flat%   sum%        cum   cum%
    22.92s   100%   100%     22.92s   100%  main.work (inline)
         0     0%   100%     22.92s   100%  main.main.func1

400% CPU: all four cores were busy for the whole run, and all of the samples landed in main.work. The scheduler’s own bookkeeping doesn’t show up in the profile at all.

Run queues and work stealing

The 296 goroutines that aren’t running wait in queues. Each P has a local run queue with 256 slots. A new goroutine goes onto the local queue of the P that created it. When that queue is full, the runtime moves half of it, plus the new goroutine, to a single global run queue.

When a P’s local queue runs dry, findRunnable in runtime/proc.go looks for work in this order: the global queue, the network poller, then the local queues of other Ps, taking half of a victim’s queue at a time. (It also checks the global queue first once every 61 scheduling rounds, so goroutines there can’t starve.) Taking work from another P is called work stealing, and it’s what keeps one core from idling while another has a backlog.

You can watch it with GODEBUG=schedtrace=500, which prints the queue lengths every 500 ms. Same 300-goroutine program, output trimmed to the queue fields:

$ GODEBUG=schedtrace=500 ./queues 2>&1 | head -6 | sed 's/gomaxprocs.*runqueue/runqueue/; s/ schedticks.*/ /'
SCHED 0ms: runqueue=0 [ 1 0 0 0 ]
SCHED 503ms: runqueue=148 [ 1 0 8 139 ]
SCHED 1006ms: runqueue=151 [ 6 13 12 114 ]
SCHED 1511ms: runqueue=131 [ 27 20 28 90 ]
SCHED 2015ms: runqueue=177 [ 2 49 3 65 ]
SCHED 2520ms: runqueue=189 [ 26 25 15 41 ]

runqueue is the global queue; the brackets are the four local queues. The fourth queue filled first (139), and the overflow went to the global queue. That queue then shrinks on every line, 139 → 114 → 90 → 65 → 41, while the other three Ps pick up work. The exact values change from run to run; an earlier run started at 207 and ended at 108.

Preemption: a loop that never yields

Before Go 1.14 a goroutine gave up its P only at certain points, such as function calls, channel operations and system calls. A loop with none of those could hold a P forever:

func main() {
	go func() {
		for {
		} // never calls anything
	}()
	time.Sleep(100 * time.Millisecond)
	fmt.Println("main got the CPU back")
}

With a single P, the spinning goroutine takes the CPU as soon as main sleeps, and main would never run again. It does:

$ GOMAXPROCS=1 go run spin.go
main got the CPU back

Since Go 1.14 the runtime preempts asynchronously. The runtime keeps one thread, sysmon, outside the scheduler: it holds no P and wakes up periodically to inspect all of them. When one goroutine has been running for more than 10 ms (forcePreemptNS in runtime/proc.go), the runtime sends that thread a signal (SIGURG on Linux). The signal handler stops the goroutine at a safe point and puts it back on a run queue, and main gets its turn.

Turning that off brings the old behavior back:

$ GOMAXPROCS=1 GODEBUG=asyncpreemptoff=1 timeout 8 ./spin; echo exit code $?
exit code 124

Exit code 124 means timeout killed the process after 8 seconds: main never got the CPU back.

The case where Go starts a thousand threads

So far the thread count has stayed flat. One program makes it follow the goroutine count:

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if os.Args[1] == "sleep" {
				time.Sleep(2 * time.Second) // the scheduler parks the goroutine
			} else {
				ts := syscall.NsecToTimespec(int64(2 * time.Second))
				syscall.Nanosleep(&ts, nil) // the thread itself blocks in the kernel
			}
		}()
	}
	time.Sleep(time.Second)
	fmt.Printf("%-8s OS threads: %d\n", os.Args[1], pprof.Lookup("threadcreate").Count())
	wg.Wait()
}
$ go run block.go sleep
sleep    OS threads: 6
$ go run block.go syscall
syscall  OS threads: 1005

Both versions wait two seconds in a thousand goroutines. The difference is where they wait:

A different run of the syscall version gave 1004; the order of magnitude doesn’t change.

Network I/O doesn’t fall into this trap. On Linux, sockets are non-blocking and registered with epoll. A goroutine that reads from a socket with no data gets parked, the thread stays free, and the network poller wakes the goroutine when data arrives. A Go server with 10,000 idle connections therefore has 10,000 parked goroutines and a handful of threads. Blocking file I/O, cgo calls and raw syscalls like the one above don’t get that treatment.

What to take from it

These measurements are from one 4-vCPU VM on Go 1.27.3. Start-up times and queue lengths will differ on other machines; the thread counts and the shape of the queues shouldn’t.

Related: Go escape analysis in 5 minutes covers when values end up on the heap instead of a goroutine’s stack.

Sources


Share this post:

Previous Post
Coolify on Hetzner: git push deploys, a panel only you can reach, and offsite Postgres backups