Goroutines, Channels and Green Threads

Topics Covered

Green Threads and M to N Scheduling

What a green thread is

One to one, M to one and M to N

Growable stacks

Blocking without blocking the carrier

The cost of a context switch

Scheduling fairness and priorities

Observability of green threads

Where green threads came back

Operating system threads give each task its own stack and let the kernel decide who runs, but they are expensive enough that a server with a hundred thousand connections cannot afford one per connection. Event loops solve the cost problem but force code into callbacks or async functions. Green threads, managed by a language runtime instead of the kernel, aim for both: the simple blocking style of threads with the low cost of an event loop. This section explains how they work and why Go, Erlang and now Java have adopted them.

What a green thread is

A green thread is a thread of execution scheduled by a user space runtime rather than by the operating system. The runtime gives each green thread its own small stack and switches between them by saving and restoring a handful of registers, without a system call or a trip through the kernel scheduler. Because the stacks start small, often a few kilobytes, and switching is cheap, a program can create hundreds of thousands or millions of them. Code running in a green thread looks like ordinary blocking code: it calls read on a socket and waits for the result, and the runtime quietly parks it and runs another green thread until data arrives. The term comes from an early Java implementation by the Green Team at Sun, which mapped all Java threads onto one OS thread; modern runtimes map them onto many.

One to one, M to one and M to N

There are three ways to map user level threads onto kernel threads. One to one, used by Java platform threads, C and Rust standard threads, gives each user thread its own kernel thread, so the kernel schedules everything and blocking is natural, but each thread is costly. M to one maps many green threads onto a single kernel thread, which is cheap but cannot use more than one core, and one blocking system call stalls everything, the problem that sank early green thread implementations. M to N maps many green threads onto a smaller pool of kernel threads, usually one per core, combining cheap threads with parallelism. Go goroutines, Erlang processes and Java virtual threads all use M to N scheduling, which requires a sophisticated runtime scheduler but gives the best of both models.

M to N scheduling multiplexes many cheap green threads onto one OS thread per core.

Growable stacks

A kernel thread reserves a fixed stack, typically 8 megabytes of virtual address space on Linux, sized for the deepest call chain the thread might ever need. Green thread runtimes avoid this by starting with tiny stacks and growing them on demand. Go starts each goroutine with a 2 kilobyte stack and checks in every function prologue whether there is room for the frame; if not, the runtime allocates a stack twice as large, copies the old one into it, adjusts pointers into the stack and continues. Stacks shrink again during garbage collection when mostly unused. Java virtual threads store their stack frames on the heap as chunks, copying them to and from the carrier thread stack when they unmount and mount. These techniques are what make a million concurrent green threads possible in a few gigabytes of memory.

A goroutine stack starts at 2 KB. When a call needs more room, the runtime copies it to a bigger stack.

Blocking without blocking the carrier

The defining trick of a green thread runtime is turning blocking calls into scheduler events. When a goroutine reads from a network socket that has no data, the Go runtime does not let the kernel thread block. Its network poller registers the socket with epoll or kqueue, parks the goroutine, and runs another one on the same kernel thread; when the socket becomes readable, the poller marks the goroutine runnable again. To the programmer, the read looked blocking; to the operating system, the thread never waited. The same mechanism underlies timers, channel operations and locks. System calls that cannot be made nonblocking, such as many file operations, are handled differently: the runtime lets the kernel thread block but hands its scheduling context to another thread, so the other goroutines keep running.

The read looks blocking to the goroutine. The runtime parks it on the poller and keeps the OS thread busy.

The cost of a context switch

The economics of green threads come down to the price of switching. An OS thread switch enters the kernel, saves the full register state including floating point and vector registers, runs the kernel scheduler, possibly changes address space mappings for a different process, and returns to user space, typically costing one to several microseconds and disturbing caches and branch predictors along the way. A green thread switch within a runtime saves only the few registers the calling convention requires, swaps a stack pointer and jumps, often in tens to a couple of hundred nanoseconds. When a server switches between tasks hundreds of thousands of times per second, the difference becomes a meaningful share of CPU time. Creation cost differs even more: spawning an OS thread involves system calls and stack mapping, while starting a goroutine or virtual thread is an allocation and a queue insertion, cheap enough to do once per request or even once per small piece of work.

Scheduling fairness and priorities

Kernel schedulers have decades of work behind them on fairness, priorities, real time classes and interaction with power management. A green thread runtime reimplements part of this in user space, and its choices differ. Most runtimes have no priorities among green threads at all: Go goroutines are all equal, and Java virtual threads ignore the priority field. Fairness comes from preemption and from round robin queues rather than from tracking how much CPU each task has used. For typical server workloads this is fine, since requests are similar and short, but workloads that need strict prioritization, such as separating latency sensitive requests from bulk background jobs, usually do so by limiting concurrency for the background work with semaphores or by running it in a separate pool or process, rather than relying on the runtime scheduler to prefer one kind of green thread over another.

Observability of green threads

Green threads complicate debugging tools designed around OS threads. A native profiler or debugger sees only the carrier threads, not the green threads multiplexed on them, so a stack sample of a Go or Java process taken with operating system tools shows runtime scheduler frames rather than the logical tasks. Each runtime therefore provides its own tools. Go offers pprof goroutine profiles, which dump the stack of every goroutine grouped by identical stacks, and the execution tracer, which shows goroutine scheduling, blocking and system calls over time. Java exposes virtual threads in thread dumps through jcmd Thread.dump_to_file, with a JSON format suited to very large numbers of threads, and in JFR events. Erlang has observer and recon for inspecting processes, mailboxes and reductions. Learning these tools is part of adopting any green thread platform.

Where green threads came back

Green threads fell out of favour in the early 2000s, when Java and others moved to one to one threading because kernels had become good at scheduling and the M to one designs could not use multiple cores. They returned when servers needed to hold hundreds of thousands of connections at once and M to N runtimes with integrated pollers made the model both cheap and parallel.

Green threads hide the event loop inside the runtime

Green threads are scheduled by the runtime, start with small growable stacks, and park on a poller instead of blocking the OS thread, so code stays in simple blocking style while scaling like an event loop. M to N scheduling, used by Go, Erlang and Java virtual threads, adds parallelism across cores.