Services

Resources

Company

Goroutine

A goroutine is a function that runs concurrently with the rest of a Go program. You start one by putting go in front of a function call, such as go handle(conn), and the call returns immediately while the function keeps running. Goroutines are cheap enough that programs routinely run thousands of them.

How it works

Each goroutine starts with a small stack, 2 KB in current Go, that the runtime grows and shrinks as needed. The Go scheduler multiplexes goroutines onto OS threads: GOMAXPROCS threads run Go code at once, by default one per CPU core. When a goroutine blocks on network I/O, a channel or a lock, the scheduler parks it and runs another on that thread.

For example, a TCP server like the Redis clone in the One2N Go bootcamp calls go handle(conn) for each client connection. With 10,000 clients connected, that is 10,000 goroutines starting at about 2 KB of stack each, about 20 MB in total, running on 8 OS threads on an 8-core machine. A word count over many files can do the same with one goroutine per file.

Why it matters in production

Goroutines are cheap but not free. A goroutine blocked forever on a channel nobody reads, or on a request with no timeout, is never collected, and a slow leak like that grows memory until the process is killed. Give each goroutine a way to finish, such as a context.Context with a deadline, wait for them with sync.WaitGroup, and watch runtime.NumGoroutine() or the pprof goroutine profile. Shared state between goroutines needs a lock or channels to avoid a race condition.

See also

On the One2N blog

References

  1. Goroutines (Effective Go)

  2. Goroutines (A Tour of Go)

Four-panel comic about goroutines: Asha has 10,000 clients to serve and one thread per client feels heavy; go handle(conn) starts a goroutine with a 2 KB stack that the runtime schedules onto OS threads; 10,000 goroutines at about 2 KB is about 20 MB on 8 threads; Asha gives every goroutine a way to finish so none leak.