Lightweight Goroutines

Lightweight Goroutines in Go: An operating system thread is a runway. It is expensive to build, there is a small fixed number of them, and while one aircraft…

The Analogy: The Control Tower and the Runways

An operating system thread is a runway. It is expensive to build, there is a small fixed number of them, and while one aircraft is sitting on it nothing else can use it. If your model of concurrency is "one thread per task", you are building a runway per flight, and you will run out at a few thousand -- each one costs a megabyte or two of reserved stack and a kernel-visible scheduling slot.

A goroutine is a filed flight plan. It costs a couple of kilobytes and a few pointers to create, and the Go runtime keeps thousands of them in the air over the same handful of runways. The control tower is the runtime scheduler: it decides which flight plan occupies which runway at each moment, and the instant a flight has to wait -- for a channel, a lock, a network read -- the tower pulls it off the runway and puts another one on. The runway is never idle just because one task is blocked.

This is why the arithmetic of Go concurrency feels wrong at first. A hundred thousand goroutines is a normal number, not a stress test, because a goroutine's stack starts at about 2 KB and grows by being copied to a bigger block when it needs more. A thread's stack is reserved up front and never shrinks. Creating a goroutine is closer in cost to allocating a small struct than to asking the kernel for anything.

Where the analogy stops: no tower announces your arrival. go f() returns immediately and gives you nothing -- no handle, no id, no return value, no way to cancel it. If main returns, every goroutine still in the air disappears mid-flight with no cleanup and no error. A goroutine blocked forever on something nobody will ever send is not an error either; it is a leak that the runtime will happily hold onto until the process exits. Every one of the remaining lessons in this module exists to answer the question this one leaves open: how do you know it finished, and how do you get the answer back?


Syntax or Core Structure

go in front of a call. That is the entire language feature. Everything else is the sync package and the channels in the next lesson.

package main

import (
	"fmt"
	"strings"
	"sync"
)

func main() {
	// WaitGroup counts outstanding work. Add before launching, never inside.
	var wg sync.WaitGroup

	// Pre-sized: every goroutine writes to its own element, so the writes
	// do not overlap and need no lock.
	bars := make([]string, 4)

	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() { // Go 1.22+: i is a fresh variable each iteration
			defer wg.Done() // runs even if the body panics
			bars[i] = strings.Repeat("*", i+1)
		}()
	}

	wg.Wait() // blocks until the counter hits zero

	// Safe to read only because Wait established a happens-before edge.
	for i, b := range bars {
		fmt.Printf("worker %d: %s\n", i, b)
	}

	// A goroutine with a parameter: the value is copied at launch time.
	wg.Add(1)
	go func(label string) {
		defer wg.Done()
		fmt.Println("done:", label)
	}("cleanup")
	wg.Wait()
}

Output:

worker 0: *
worker 1: **
worker 2: ***
worker 3: ****
done: cleanup

The output is deterministic even though the four workers ran in an unspecified order, because nothing is printed until after wg.Wait() and each goroutine wrote to a different slice element. Reverse those two facts -- print from inside the goroutines, or have them all append to the same slice -- and the program becomes both unordered and racy. Note also that bars[i] = ... looks like shared-slice mutation but is not: the slice header is only read, and each element is written by exactly one goroutine.


Technical Depth: What the Runtime Is Actually Doing

G, M and P

The scheduler is described in the runtime source with three letters, and knowing them makes every profiling tool and stack dump readable.

LetterStands forWhat it is
GgoroutineThe flight plan: a stack, a program counter, and a status. Created by go. Cheap, unbounded in count.
MmachineAn actual OS thread. The only thing that can execute code. Created by the runtime on demand.
PprocessorA scheduling context -- a run queue plus the permission to run Go code. There are exactly GOMAXPROCS of them.

A G runs only when it is attached to a P that is attached to an M. GOMAXPROCS (default: the number of logical CPUs) caps how many goroutines run Go code at the same instant; it does not cap how many exist, and it does not cap threads. Each P keeps a local run queue, with a global queue and work stealing between Ps when one runs dry.

What happens when a goroutine blocks

Blocking onEffect
Channel, mutex, WaitGroup, time.SleepThe G is parked: taken off the M and stored in a wait list. The P immediately picks up another G. No thread is consumed.
Network read or writeParked the same way. The runtime's netpoller (epoll/kqueue/IOCP) wakes it. This is why blocking-style Go code scales like async code in other languages.
A real blocking syscall (file I/O on most systems, cgo)The M is stuck in the kernel, so the runtime detaches the P and hands it to another M. Thread count can exceed GOMAXPROCS here; the default limit is 10,000 threads.
A tight loop with no function callsNothing to park on. Before Go 1.14 this could starve the P forever; since 1.14 the runtime asynchronously preempts it with a signal after roughly 10 ms.

Stacks grow, they do not overflow

A goroutine starts with a small stack (2 KB at the time of writing -- treat the number as an implementation detail). Every function with locals checks the stack bound on entry; when it would overflow, the runtime allocates a stack twice the size, copies the frames over and rewrites the pointers into them, then resumes. That copying is why Go can afford tiny initial stacks, and it is also why taking the address of a local is safe: the compiler and runtime know about every pointer. Runaway recursion eventually hits a hard ceiling (1 GB on 64-bit by default) and panics with stack overflow rather than corrupting memory.

Concurrency is not parallelism

Concurrency is structure: independent tasks that could interleave. Parallelism is execution: tasks literally running at the same instant. GOMAXPROCS=1 gives you a fully concurrent program with zero parallelism, and correct concurrent code behaves identically -- just slower on multiple cores. If your program only passes with GOMAXPROCS=1, it is broken, not tuned.

WaitGroup rules

  • Add must happen before the go statement. wg.Add(1) inside the new goroutine races with Wait and can let Wait return early.
  • Done belongs in a defer, so a panic or an early return still decrements.
  • A WaitGroup must not be copied. Pass *sync.WaitGroup, or capture it by closure as above. A WaitGroup field in a struct makes that struct uncopyable in practice.
  • Reuse is allowed only after Wait has returned and all Add calls for the next round happen after that.
  • Negative counter means Done was called too often: panic: sync: negative WaitGroup counter.

How goroutines leak

CauseFix
Sending on a channel nobody will receive fromBuffer it, or give the receiver a way to keep reading (select with a done case).
Receiving from a channel nobody will closeClose on the producer side; for range ch then ends.
Waiting on a lock the owner never releasesdefer mu.Unlock(), always.
No cancellation pathcontext.Context -- Module 10.

Leaks are quiet: memory grows and runtime.NumGoroutine() climbs, but nothing fails. Print that number in a long-running service and watch its shape; net/http/pprof's goroutine profile (Module 11) names the exact line every leaked goroutine is parked on.

The race detector is not optional

go test -race, go run -race, go build -race. It instruments every memory access and reports unsynchronised access from two goroutines with both stacks. It costs roughly 5-10x CPU and a few times the memory, so it is a CI and development tool -- but it finds real bugs that no amount of reading finds, and a race that "never happens" on your laptop happens on a 64-core machine. It only reports races it actually observes, so exercise the concurrent paths.

main is not special, except in one way

main runs on a goroutine like everything else. But when it returns, the process exits: no waiting, no defer in other goroutines, no flushing. Every "my goroutine printed nothing" bug is this. Likewise os.Exit skips all deferred functions everywhere, and runtime.Goexit terminates just the calling goroutine after running its defers.


Real World Example: A Parallel Pass Over a Batch, With Ordered Output

The most common real use of bare goroutines is not a worker pool with channels -- that is the next lesson. It is a parallel pass over a slice, where the work is already known up front and each item's answer belongs in a known slot.

package main

import (
	"fmt"
	"strings"
	"sync"
)

type outcome struct {
	words int
	err   error
}

func analyze(i int, text string) outcome {
	if strings.TrimSpace(text) == "" {
		return outcome{err: fmt.Errorf("doc %d: empty document", i)}
	}
	return outcome{words: len(strings.Fields(text))}
}

// Each goroutine owns a contiguous stripe of the output slice, so no two
// goroutines ever write the same memory: no mutex, no channel, no race.
func analyzeAll(docs []string, workers int) ([]outcome, []string) {
	outs := make([]outcome, len(docs))
	notes := make([]string, workers)

	size := (len(docs) + workers - 1) / workers // ceiling division

	var wg sync.WaitGroup
	for w := 0; w < workers; w++ {
		// Declared inside the loop body, so each closure gets its own pair
		// regardless of Go version.
		start := w * size
		end := min(start+size, len(docs)) // min: builtin since Go 1.21
		if start >= end {
			notes[w] = fmt.Sprintf("worker %d: idle", w)
			continue
		}
		notes[w] = fmt.Sprintf("worker %d: docs [%d:%d)", w, start, end)

		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := start; i < end; i++ {
				outs[i] = analyze(i, docs[i])
			}
		}()
	}
	wg.Wait() // the only synchronisation the whole design needs

	return outs, notes
}

func main() {
	docs := []string{
		"go routines are cheap",
		"",
		"share memory by communicating",
		"   ",
		"the scheduler multiplexes goroutines onto threads",
		"stacks start small and grow",
		"do not leak goroutines",
	}

	outs, notes := analyzeAll(docs, 3)

	for _, n := range notes {
		fmt.Println(n)
	}

	ok, failed, total := 0, 0, 0
	for i, o := range outs {
		if o.err != nil {
			failed++
			fmt.Printf("doc %d: error: %v\n", i, o.err)
			continue
		}
		ok++
		total += o.words
		fmt.Printf("doc %d: %d words\n", i, o.words)
	}
	fmt.Printf("ok=%d failed=%d words=%d\n", ok, failed, total)
}

Output:

worker 0: docs [0:3)
worker 1: docs [3:6)
worker 2: docs [6:7)
doc 0: 4 words
doc 1: error: doc 1: empty document
doc 2: 4 words
doc 3: error: doc 3: empty document
doc 4: 6 words
doc 5: 5 words
doc 6: 4 words
ok=5 failed=2 words=23

The output is fully deterministic, and that is the point. The three stripes ran in an unknown order at an unknown degree of overlap, but the answer for document 4 is written to outs[4] by exactly one goroutine, and nothing reads outs until wg.Wait() returns. Ordering the work and ordering the results are separate problems, and this design only solves the second one -- which is usually all you needed.

errors travel in the same slot as the answer, not out of band. Because outcome carries both, an error from document 1 does not need a mutex-protected error slice, a channel, or an errors.Join across goroutines. Aggregation happens in the sequential loop afterwards, where counting is trivially correct. Notice that no goroutine formats anything for the user; they compute, main reports.

Bounding is structural: three goroutines, not seven. Launching one goroutine per document would work here, but it stops working when "document" means "HTTP request" or "database query", where 10,000 at once is a self-inflicted outage. Striping gives a fixed, tunable degree of parallelism with no semaphore. Its weakness is the flip side: if document 4 takes a hundred times longer than the rest, worker 1 finishes last and workers 0 and 2 sit idle. That is the exact problem a job channel solves, which is the next lesson.

*Look at what is not here.* No lock, no channel, no atomic, no sync.Map, no ordering primitive -- because the memory was partitioned before any goroutine started. This is the cheapest correct concurrency there is, and it is worth asking for every concurrent design whether the shared state can be split instead of guarded. When it can, the race detector has nothing to find.


Common Mistakes

  1. Letting main return while goroutines are still working. No output, no error, no clue. wg.Wait(), or block on something. The reverse mistake -- time.Sleep(time.Second) "to let them finish" -- is not synchronisation, it is a slower flake.
  2. wg.Add(1) inside the goroutine. Wait can observe a zero counter before the goroutine ever runs and return immediately. Add on the launching side, every time.
  3. Forgetting defer on wg.Done(). An early return or a panic in the body leaves the counter above zero and Wait blocks forever: fatal error: all goroutines are asleep - deadlock! if nothing else is runnable, or a silent hang if something is.
  4. Copying a WaitGroup or a Mutex by passing it by value or by copying its enclosing struct. Each copy has its own counter. go vet catches the obvious cases.
  5. Appending to a shared slice from several goroutines. append reads and writes the header and may reallocate; two goroutines doing it will lose entries or corrupt the slice. Write to pre-sized indices, or collect through a channel.
  6. Incrementing a shared counter without protection. total++ from four goroutines is the textbook race and the detector's favourite finding. Use atomic.Int64, a mutex, or per-goroutine subtotals summed after the join.
  7. Assuming GOMAXPROCS bounds goroutine count or thread count. It bounds neither. Blocking syscalls create extra threads; go creates unbounded goroutines.
  8. Launching one goroutine per item over an unbounded input. Fine for 7 documents, fatal for 700,000 rows or per-request fan-out. Bound it -- stripes, a pool, or a semaphore.
  9. Expecting a return value from go f(). The statement has no value, and go on a function returning something silently discards it. Write results into memory you own, or send them on a channel.
  10. Recovering "globally" from a goroutine panic. recover only works in the panicking goroutine's own stack. An unrecovered panic in any goroutine kills the whole process, so if a goroutine runs untrusted work, it needs its own defer/recover.
  11. Trusting a clean run. The race detector reports only what it observes, and a race that never shows up on 4 cores appears immediately on 64. Run the concurrent tests with -race and with -count above 1.

Best Practices

  • Launch goroutines only where you can also answer "who waits for this, and how does it stop?" If you cannot, do not launch it yet.
  • Prefer partitioning shared state over guarding it: disjoint indices need no lock at all.
  • Keep wg.Add next to the go statement and wg.Done in a defer on the first line of the body.
  • Bound parallelism to a number you chose deliberately -- stripes, a fixed pool, or golang.org/x/sync/errgroup with SetLimit.
  • Do the reporting and aggregation sequentially after the join; goroutines compute, the caller formats.
  • Run tests with -race in CI, and make the concurrent ones cheap enough that nobody disables it.
  • Never assume execution order between goroutines, and never write a test that depends on one. If order matters, express it with a channel or a lock.
  • Watch runtime.NumGoroutine() in long-running services; a monotonically rising count is a leak, not load.

Practice Exercises

  1. Delete wg.Wait() from analyzeAll and run the program several times. Record what changes in the output and explain, in terms of the printing loop, why the notes lines still appear correctly while the doc lines do not.
  2. Replace the striping with one goroutine per document and add a shared total variable that each goroutine increments directly. Run it under go run -race and describe which two accesses the detector pairs up.
  3. Make analyzeAll bound its parallelism with a buffered chan struct{} semaphore of size workers instead of stripes, keeping the output identical. Then explain which of the two designs handles one very slow document better, and why.
  4. Write a function that launches a goroutine which panics, with the panic recovered inside that goroutine and turned into an error stored in a caller-visible field. Confirm the process survives, then remove the recover and record what the program prints instead.