The previous article introduced goroutines as Go's basic unit of concurrent execution and described how channels let them communicate. It never said what a goroutine actually is. A goroutine borrows ideas from OS threads, green threads and coroutines, and this article goes through each of them to show which parts Go kept. Once you know how the Go scheduler manages goroutines, it makes sense that you can launch a million of them, and that concurrent Go code is written differently from concurrent code in most other languages.

Every Go program has at least one goroutine

Before you launch a single go statement, your program is already concurrent: the main function itself runs inside a goroutine, conventionally called the main goroutine. When main returns, the Go runtime shuts down the entire program, no matter how many other goroutines are still running.

Any function can be promoted to a goroutine with the go keyword:

Go
package mainimport (	"fmt"	"sync")func greet(name string) {	fmt.Printf("hello, %s\n", name)}func main() {	var wg sync.WaitGroup	wg.Add(2)	go func() {		defer wg.Done()		greet("Alice")	}()	go func() {		defer wg.Done()		greet("Bob")	}()	fmt.Println("goroutines launched")	wg.Wait()}

The statement go greet("Alice") returns immediately: it schedules the function to run concurrently and moves on to the next line without waiting. The output order of the two greetings is not guaranteed; either can run first, or both can run simultaneously on different CPU cores.

OS threads

The most familiar concurrency primitive is the OS thread, so we start there.

A thread is the OS's unit of CPU scheduling. Every process has at least one thread (the one that runs main), and can create additional threads to do work concurrently. The OS kernel schedules threads onto CPU cores, preempts them when their time slice expires, and switches between them as needed.

OS threads are expensive in three ways:

  • Stack size: the OS typically allocates a fixed stack of 1–8 MB per thread at creation time. Most of that space goes unused for most threads.
  • Context switch cost: switching between threads requires the kernel to save and restore dozens of CPU registers, switch the memory protection context, and flush parts of the CPU pipeline. This takes thousands of nanoseconds.
  • Kernel involvement: creating, destroying, and scheduling threads all require system calls, which means transitions from user space into the kernel and back.

For servers handling thousands of simultaneous connections, creating one OS thread per connection quickly becomes impractical. The stacks alone for 10,000 threads at 2 MB each add up to 20 GB.

Green threads

One answer to OS thread overhead was green threads: threads managed entirely in user space by a language runtime or virtual machine instead of the OS kernel.

Green threads are much lighter than OS threads. The runtime controls their creation and scheduling, so there is no kernel involvement. Stacks can start small and grow only as needed. Context switches happen entirely in user space, with no system call and no trap into the kernel.

The limitation of early green thread implementations was that they typically used an M:1 model: all green threads multiplexed onto a single OS thread. This meant:

  • No true parallelism: at most one green thread ran at a time, on one CPU core.
  • A single blocking system call (like a file read) would block the entire program, since it blocked the one underlying OS thread.

Some runtimes addressed the second problem by wrapping blocking calls, but the single-thread parallelism ceiling remained. Early versions of Java used green threads with this limitation before switching to native OS threads in Java 1.2.

Coroutines

A coroutine is a function that can suspend its own execution and transfer control to another coroutine explicitly. The scheduler doesn't decide when to preempt it. The function cooperates instead: it yields at defined points, passes control elsewhere, and resumes later from where it left off.

Coroutines fit programs that deal with sequences of events. An HTTP handler written as a coroutine can suspend while waiting for a database query, let other handlers run, and resume when the result arrives, with no callbacks and no full OS thread per request.

Modern languages have embraced coroutines under different names: Python's async/await, Kotlin's suspend functions, JavaScript's generators. All of them use cooperative scheduling: the programmer explicitly marks where a function may yield.

That cooperation is also the constraint. A coroutine that never yields blocks everything waiting behind it, so CPU-bound code running a tight loop without yielding starves the other coroutines, and developers have to be careful about when and where they yield.

Goroutines: the synthesis

Goroutines take something from each of these models and avoid most of their limitations.

OS threadsGreen threads (M:1)CoroutinesGoroutines
Managed byOS kernelRuntimeRuntimeGo runtime
Initial stack1–8 MB fixedVariesVaries~2–4 KB, grows
SchedulingPreemptiveCooperativeCooperativePreemptive (Go 1.14+)
True parallelismYesNoNoYes (M:N)
Context switch~1–10 µs (kernel)~100 ns (user space)~100 ns~100 ns
Blocking a thread?YesYes (M:1)DependsNo, runtime parks the goroutine

The difference is the M:N model: M goroutines are multiplexed onto N OS threads, where N is typically the number of available CPU cores. Goroutines get the parallelism of OS threads and the low cost of green threads, and the runtime decides when to preempt them, so you never mark yield points by hand.

The Go scheduler

Go's scheduler is called the GMP scheduler, after its three components:

  • G: a goroutine
  • M: a machine (an OS thread)
  • P: a processor (a logical CPU, controlled by GOMAXPROCS)

Each P has a local run queue: a list of goroutines waiting to run. A P is always attached to exactly one M (OS thread), and that M runs one goroutine at a time. The runtime creates as many P's as GOMAXPROCS specifies (defaulting to the number of CPU cores) and distributes work among them.

┌──────────────────────────────────────────────────────┐
│                     Go Runtime                       │
│                                                      │
│   ┌──────────────────┐   ┌──────────────────┐        │
│   │        P1        │   │        P2        │        │
│   │   local queue    │   │   local queue    │        │
│   │  [G3] [G4] [G5]  │   │  [G6] [G7]       │        │
│   └────────┬─────────┘   └────────┬─────────┘        │
│            │                      │                  │
│           M1 (OS thread)         M2 (OS thread)      │
│            │                      │                  │
│         Core 1                 Core 2                │
│                                                      │
│   Global queue: [G8] [G9] [G10] ...                  │
└──────────────────────────────────────────────────────┘

When a P's local queue runs dry, it steals goroutines from another P's queue, typically half of that P's backlog. Work stealing keeps every P busy as long as there are goroutines to run, and you don't have to balance the load yourself.

You can read and control GOMAXPROCS at runtime:

Go
import (	"fmt"	"runtime")func main() {	// read the current value (0 = query without changing)	procs := runtime.GOMAXPROCS(0)	fmt.Printf("using %d logical processors\n", procs)}

In production, the default (number of CPU cores) is almost always correct, so you rarely need to change it.

Blocking without blocking

A big part of the scheduler's job is handling goroutines that block. When a goroutine waits for a channel receive, a mutex, or a network read, it has to pause, and it shouldn't keep its OS thread occupied while it does.

The runtime handles this transparently:

  1. The goroutine calls an operation that would block (e.g., reading from an empty channel).
  2. The runtime parks the goroutine: it removes it from the run queue and marks it as waiting.
  3. The P immediately schedules the next goroutine from its local queue onto the same M (OS thread).
  4. When the blocking condition resolves (a value is sent to the channel), the runtime unparks the goroutine and puts it back into a run queue to be scheduled again.
Traditional threads:              Goroutines:

Thread 1 → blocks on I/O         G1 → blocks on I/O
           waiting...                 ↓ runtime parks G1
           waiting...             G2 → runs on the same OS thread
           waiting...             G3 → runs on the same OS thread
Thread 1 ← resumes                G1 ← unparked when I/O completes

The left side wastes an OS thread for the entire duration of the I/O, while the right side keeps the OS thread doing useful work. That is how a Go HTTP server handles tens of thousands of simultaneous connections on a handful of OS threads: each connection gets a goroutine, and a parked goroutine holds no OS thread.

For blocking system calls (like reading from a file), the runtime uses a different mechanism: it detaches the P from the M before the system call, attaches the P to a different M (creating one if needed), and continues running other goroutines. When the system call returns, the runtime tries to attach the original M back to a P.

Preemption

Early versions of Go used purely cooperative scheduling: a goroutine only yielded at specific points, such as function calls, channel operations and explicit calls to runtime.Gosched(). A tight loop with no function calls could monopolize a P indefinitely, starving other goroutines on that processor.

Go 1.14 introduced asynchronous preemption: the runtime sends a signal to an OS thread, which interrupts whatever goroutine is running and gives the scheduler a chance to switch to another. Goroutines don't need to yield explicitly, and CPU-bound code no longer starves the scheduler.

Go
// Before Go 1.14, this loop starved other goroutines on the same P.// From Go 1.14 onward, the scheduler preempts it periodically.go func() {	for {		// tight CPU-bound loop — no function calls, no yield points		result := heavyComputation()		_ = result	}}()

With asynchronous preemption the scheduler handles fairness on its own, which is one reason you rarely need runtime.Gosched() in modern Go.

What this means in practice

The GMP model has practical consequences for how you write Go:

Goroutines are cheap, so use them freely. Launching a goroutine costs a few microseconds and ~2 KB of memory. If a task can run independently, put it in a goroutine. You don't need thread pools or work queues to keep the overhead down; the runtime takes care of that.

Blocking is fine. Blocking on a channel, waiting for a mutex or sleeping parks the goroutine without wasting an OS thread. You do not need to convert every blocking call to an async callback to avoid starving the runtime.

GOMAXPROCS controls parallelism, not concurrency. Setting GOMAXPROCS(1) makes the program single-threaded from the OS perspective, but goroutines still run concurrently via time-slicing on that one thread, so race conditions can still happen and the race detector still applies.

Coordination is still your job. The scheduler decides which goroutine runs where, but who sends to whom, who waits for what and how cancellation propagates are up to you, and you express them with channels, sync and context.