Goroutines
A goroutine is a lightweight function managed by Go's own runtime scheduler rather than the operating system, letting a single program run hundreds of thousands of concurrent tasks cheaply instead of the handful an OS thread model allows.
WHY IT EXISTS A server handling many thousands of simultaneous connections needs a way to run that many tasks concurrently, but a real operating system thread costs megabytes of stack space and real kernel scheduling overhead, so spawning one thread per connection stops working at any real scale. Goroutines exist so a Go program can express that same one-task-per-unit-of-work model, without a programmer hand-rolling callback chains or a thread pool, while staying cheap enough to spawn by the hundreds of thousands.
THE MENTAL MODEL A goroutine is a lightweight ticket handed to Go's own scheduler that says run this whenever you get a chance, rather than a request to the operating system for a dedicated worker. Go's runtime multiplexes many of these tickets onto a small number of real OS threads, the way many passengers share a handful of taxis instead of each getting a private car, so concurrency stops being limited by how many threads the OS can afford to hand out.
HOW IT WORKS Starting a goroutine with the go keyword begins it with an initial stack of roughly 2 kilobytes that grows and shrinks as needed, far smaller than a typical fixed multi-megabyte OS thread stack. Go's M:N scheduler maps M goroutines onto N OS threads, cooperatively switching between goroutines at function calls, channel operations, and other safe points, so thousands of goroutines can make progress on just a handful of real threads. GOMAXPROCS controls how many OS threads can execute Go code at once. Goroutines are meant to coordinate through channels rather than shared memory guarded by locks, following Go's own mantra of sharing memory by communicating instead of communicating by sharing memory.
WHEN IT MATTERS It matters for any server or workload that fans out into many simultaneous, mostly idle tasks, like handling concurrent network connections. The footgun is that goroutines can leak: one blocked forever reading from a channel nobody will ever write to just sits there consuming its stack for the life of the program, since Go has no forced cancellation, only cooperative signaling through a context or a closed channel.
ONE CONCRETE EXAMPLE Go's net/http package spawns one goroutine per incoming request automatically. Serving 10,000 simultaneous slow requests costs only tens of megabytes of total goroutine stack space, work that would demand 10,000 real OS threads and many gigabytes of stack in a naive thread-per-request server.
Read the original → go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.