Go Reference ยท Concurrency and Context
Go sync package
Reference for the Go sync package: Mutex, RWMutex, WaitGroup, Once, Pool, Map and Cond, when each is the right tool, and how it compares to channels.
The package sync contains the low-level building blocks for coordinating goroutines that share memory. When several goroutines touch the same variable and at least one of them writes, you need to order those accesses, or the program has a data race. The types in sync do that.
Channels are Go's preferred way to pass ownership of data between goroutines, and sync is the right choice when goroutines share state in place: a counter, a cache, a connection pool, or a "wait until all workers are finished" barrier.
var mu sync.Mutex mu.Lock() counter++ mu.Unlock()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
| Type or function | Purpose |
|---|---|
sync.Mutex |
Mutual exclusion lock: one goroutine at a time. |
sync.RWMutex |
Many readers or one writer. |
sync.WaitGroup |
Wait for a set of goroutines to finish. |
sync.Once, OnceFunc, OnceValue, OnceValues |
Run initialization exactly once. |
sync.Pool |
Cache of temporary objects to reduce allocations. |
sync.Map |
Concurrent map for specific access patterns. |
sync.Cond |
Wait for and announce a condition: Wait, Signal, Broadcast. |
sync/atomic |
Lock-free operations on single values; see sync/atomic. |
func NewCond(l Locker) *Cond func (c *Cond) Wait() func (c *Cond) Signal() func (c *Cond) Broadcast()
Locker is the interface { Lock(); Unlock() } that Mutex and RWMutex satisfy. Cond.Wait atomically unlocks the mutex and sleeps, then locks it again before returning.
Usage notes
- Never copy a sync type after first use. Mutexes, WaitGroups, Once and Cond contain state; copying them (by value receivers, assignment, passing by value) creates a second, unrelated lock.
go vetreports this ascopylocks. Embed or hold them by value in a struct and pass the struct by pointer. - Zero values are ready to use for
Mutex,RWMutex,WaitGroup,OnceandMap.CondandPoolneed constructors or aNewfield. - Keep critical sections short and never call unknown code, block on a channel or do I/O while holding a lock if you can avoid it.
- Detect races with
go test -raceorgo run -race; this is the best tool for spotting a missing lock. (The race detector is not available on our online runner.) - Channels or locks? Use channels to hand off work or results and to coordinate sequences; use a mutex to protect a data structure that several goroutines read and update in place.
- Deadlocks: locking a mutex twice in one goroutine, or two goroutines locking two mutexes in opposite order, blocks forever. When all goroutines are asleep the runtime aborts with
fatal error: all goroutines are asleep - deadlock!. Condis rarely needed. A closed channel or a channel of signals is usually simpler;Condremains useful for broadcast wake-ups on shared state.