Services

Resources

Company

/

Goroutine

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)

Goroutine diagram: the call go handle(conn) starts one goroutine per client, drawn as a grid of yellow dots labelled 10,000 goroutines. An arrow leads to the Go scheduler, which fans them out onto 8 OS threads, each running one goroutine at a time. One dot in the grid is red, labelled blocked forever: leak. Underneath, 10,000 x 2 KB stack = about 20 MB.

Putting this into practice?

Talk to One2N about our backend engineering services

Talk to One2N about our backend engineering services