Go Concurrency#
“Do not communicate by sharing memory; instead, share memory by communicating.”
— Rob Pike
Concurrency in Go is built on a fundamentally different philosophical foundation than traditional OS thread-based multithreading. By embedding C.A.R. Hoare’s CSP (Communicating Sequential Processes) model directly into the core of the language, Go emphasizes transferring data ownership via communication rather than lock contention and complex shared-state synchronization.
Two Pillars of Go Concurrency: sync.Mutex vs. Channel#
Go provides two complementary yet contrasting synchronization primitives for handling concurrent workflows:
| Dimension | sync.Mutex (Traditional Model) | Channel (CSP Model) |
|---|---|---|
| Core Philosophy | Communicating by sharing memory | Sharing memory by communicating |
| Data Location | Fixed at a specific memory address (shared variable) | Moves across goroutines through communication pipes |
| Synchronization | Mutual exclusion (locks) guarding critical sections | Passing data ownership like a relay baton |
| Primary Risks | Deadlocks, data races, lock contention, complex state tracking | Goroutine leaks, unbuffered channel deadlocks |
| Ideal Use Cases | In-memory caches, atomic counters, fine-grained state protection | Worker queues, data processing pipelines, event coordination |
(1) sync.Mutex: Communicating by Sharing Memory#
Multiple goroutines concurrently access a single shared memory location. To preserve consistency, goroutines acquire a mutual exclusion lock (Lock()), read or write state, and release the lock (Unlock()). Goroutines communicate their progress indirectly through shared state guarded by locks.
(2) Channel: Sharing Memory by Communicating#
Instead of competing for locks over shared memory, goroutines pass the ownership of the data directly through a typed communication channel. The receiving goroutine exclusively owns the received data, completely eliminating data races without explicit lock management.