Go Concurrency Primitives
Go provides several tools to manage complex concurrent workflows. Beyond basic goroutines and channels, you often need these primitives for synchronization and data safety.
1. WaitGroups (sync.WaitGroup)
Used to wait for a collection of goroutines to finish.
2. Mutexes (sync.Mutex)
Used to protect "critical sections" of code where you access shared data. A Mutex (Mutual Exclusion) ensures only one goroutine can access the data at a time.
3. Atomic Counters (sync/atomic)
For simple numeric updates (like a global counter), the atomic package is much faster than a Mutex because it uses low-level hardware instructions.
4. Worker Pools
A common pattern to limit resources by running a fixed number of goroutines that process a queue of work.
Summary Table
| Primitive | Use Case |
|---|---|
| Channels | Passing data between goroutines. |
| WaitGroup | Waiting for multiple tasks to complete. |
| Mutex | Protecting complex shared objects (maps, structs). |
| Atomic | Updating simple numbers (counters, flags). |
| Worker Pool | limiting the amount of concurrent work. |