Golang is designed to provide for easy-to-use concurrent programming.
- Goroutines are lightweight green threads managed by the language runtime.
- Many synchronisation primitives have first-class support.
- Channels are a typed “pipe” that can send and receive values. These are the idiomatic way to implement synchronisation in Go.
- The usual primitives, like mutexes, condition variables, and semaphores are also built-in.
Programming
One pitfall of concurrent Go is that it’s easy to exhaust the runtime library or RPC backend. Consider this case:
- We have a long-running function on a loop.
- In each iteration of the loop, we spawn goroutines.
- The rest of the function continues execution, and will eventually loop again on a timer.
- More goroutines are spawned.
- Then, the RPC backend is exhausted, or the runtime library is exhausted, or synchronisation is essentially impossible (deadlocks or inability to acquire a mutex).