2026-04-27 · Go
Parallel Programming: Atomic, Mutex, Semaphore
Introduction
Most programs can use concurrency to run simply, safely, and efficiently. With the advent of multicore CPUs and the demand for performance in specific scenarios, parallelism offers another way to improve execution efficiency. This article uses Go to review data sharing techniques for parallel programming:
- Atomic operations
- Mutexes
- Semaphores
Race Conditions
Program output depends on an uncontrolled sequence or timing of events, typically when shared resources are accessed or modified simultaneously in parallel.
For example, the following program is unlikely to produce the same value for count every time, because count++ actually consists of three steps:
- Read
count - Add one
- Write back to
count
var count int
var wg sync.WaitGroup
for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() count++ }()}
wg.Wait()Atomic Operations
If we replace the code that causes the race condition with an indivisible atomic operation, its steps can no longer interleave with other operations, eliminating the race condition:
import "sync/atomic"
var count int64
atomic.AddInt64(&count, 1)- Characteristics
- Lowest overhead and best performance
- Suitable only for operations on a single variable
- When to use
- Counters (request counts)
- State flags
- Pointer replacement (unsafe.Pointer)
Mutexes
import "sync"
var mu sync.Mutexvar count int
mu.Lock()count++ // Critical sectionmu.Unlock()- Characteristics
- Can protect arbitrarily complex logic
- Easy to understand and broadly applicable
- Incurs lock contention overhead
- When to use
- Complex state updates
- Complex data operations (struct / map)
- When a critical section needs protection
Semaphores
sem := make(chan struct{}, 3) // At most 3 running simultaneously
for i := 0; i < 10; i++ { go func() { sem <- struct{}{} // acquire defer func() { <-sem }() // release
// do work }()}- Characteristics
- Controls the number of operations running simultaneously
- Does not directly protect data
- Commonly used to limit resource usage
- When to use
- API rate limiting
- DB connection pools
- Worker pool control
Stateful Goroutines
package main
import ( "fmt" "sync" "sync/atomic")
type op struct { action string // "deposit" | "withdraw" | "balance" amount int resp chan result}
type result struct { balance int ok bool}
func bankManager(ops chan op) { balance := 0 for o := range ops { switch o.action { case "deposit": balance += o.amount o.resp <- result{balance: balance, ok: true} case "withdraw": if balance >= o.amount { balance -= o.amount o.resp <- result{balance: balance, ok: true} } else { o.resp <- result{balance: balance, ok: false} } case "balance": o.resp <- result{balance: balance, ok: true} } }}
func main() { ops := make(chan op) go bankManager(ops) // The sole goroutine that owns balance
var wg sync.WaitGroup var successCount uint64
// Simulate 5 users performing operations simultaneously actions := []struct { action string amount int user string }{ {"deposit", 1000, "Alice"}, {"deposit", 500, "Bob"}, {"withdraw", 200, "Alice"}, {"withdraw", 9999, "Bob"}, // Insufficient funds {"balance", 0, "Charlie"}, }
for _, a := range actions { wg.Add(1) a := a go func() { defer wg.Done() resp := make(chan result, 1) ops <- op{action: a.action, amount: a.amount, resp: resp} r := <-resp if r.ok { atomic.AddUint64(&successCount, 1) fmt.Printf("[%s] %-8s %4d → Balance: %d\n", a.user, a.action, a.amount, r.balance) } else { fmt.Printf("[%s] %-8s %4d → Failed, insufficient funds (available: %d)\n", a.user, a.action, a.amount, r.balance) } }() }
wg.Wait() close(ops) fmt.Printf("\nSuccessful operations: %d\n", successCount)}- Characteristics
- A single goroutine exclusively owns the state; other goroutines send requests through channels
- State access is serialized, while the rest of the business logic still runs concurrently
- No explicit lock management required
- More complex logic, but correctness is easier to reason about
- When to use
- State requires centralized management, and multiple channels are already coordinating work
- Managing multiple mutexes is error-prone and difficult to maintain
Share Memory by Communicating, or Communicate by Sharing Memory?
Although Go has the motto “Share memory by communicating; don’t communicate by sharing memory,” it does not enforce a particular programming style.
- Mutex approach: Any goroutine can access the data directly, using a lock to wait its turn
- Stateful goroutine: The data has a single owner; everyone else must communicate