Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 147 ยท Concurrency

The sync Package

Learn Go's sync package - Mutex and RWMutex for shared state, Once, OnceFunc and OnceValue, Cond, sync.Map and sync.Pool, plus copied locks, lock granularity and deadlocks.

Channels are not the only way for goroutines to cooperate. Sometimes several goroutines simply need to read and update the same data: a counter, a cache, a map of sessions. Passing that data through a channel would be awkward, and a lock is the simpler tool. The standard library package sync provides the building blocks: mutexes, one-time initialization, condition variables, a concurrent map and an object pool. You already used sync.WaitGroup in Goroutines; this lesson covers the rest.

The golden rule behind all of it: if two goroutines access the same variable at the same time and at least one of them writes, you have a data race, and the result is undefined. A lock removes the race by letting only one goroutine into the critical section at a time.

Why locks are needed

Even counter++ is not one step. The computer reads the value, adds one, and writes it back. If two goroutines do this at once, one update can overwrite the other, and increments get lost. The program below starts 50 goroutines that each increment one counter 1,000 times, so correctness depends on the lock:

Go A counter protected by a Mutex

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.

The result is always count: 50000. Without the mutex, the total would usually be smaller and different on every run.

sync.Mutex

A sync.Mutex ("mutual exclusion") has two methods: Lock and Unlock. While one goroutine holds the lock, any other goroutine calling Lock waits. The zero value is an unlocked mutex, ready to use, so a struct field mu sync.Mutex needs no setup (make the zero value useful).

Conventions that keep mutex code correct:

  • Put the mutex next to the data it protects, in the same struct, and document which fields it guards.
  • Lock, then immediately defer Unlock() (defer). That releases the lock on every return path, even a panic.
  • Keep the critical section short. Do not call slow things (network, disk) while holding a lock if you can avoid it.
  • Do not leak the protected data. Returning a map or slice that the lock guards lets callers read it without the lock.

There is also TryLock, which returns false instead of waiting. The documentation itself warns that it is rarely correct to use, so treat it as a last resort.

A concurrency-safe map

Built-in maps are not safe for concurrent use: concurrent writes make the runtime crash with fatal error: concurrent map writes. Wrap the map in a struct with a mutex:

Go A thread-safe word counter

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.

The output is a 4, b 2, c 3. The keys are sorted because map iteration order is random. Snapshot returns a clone so that the caller can iterate freely without holding the lock.

sync.RWMutex

When data is read very often and written rarely, a plain mutex is wasteful: readers block each other even though reads do not conflict. A sync.RWMutex allows many readers at once or one writer:

  • RLock / RUnlock for reading (shared),
  • Lock / Unlock for writing (exclusive).
Go Many readers, one writer

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.

All four readers print dark: [dark dark dark dark]. An RWMutex has more bookkeeping than a Mutex, so it only pays off when reads dominate and the critical sections are not tiny. If in doubt, start with Mutex and measure. Never upgrade a read lock to a write lock by calling Lock while holding RLock: that deadlocks.

Once: do something exactly one time

sync.Once runs a function exactly once, no matter how many goroutines call it, and every caller waits until that first run has finished. It is the standard tool for lazy initialization and singletons:

Go sync.Once for lazy setup

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.

loading config (runs once) appears a single time even though five goroutines asked for the config. The second line is production. Because Do waits, no caller can ever see a half-built config.

OnceFunc, OnceValue and OnceValues

Since Go 1.21 the package has helpers that wrap a function so it runs once and returns its cached result. They remove the need for separate variables:

Go OnceFunc, OnceValue and OnceValues

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.

You see hello, printed once once, computing the answer... once followed by 42 42, and parsing... once followed by 123 <nil> twice. If the wrapped function panics, the panic is re-raised on every call. Use OnceValue for the common "compute a value lazily" case.

sync.Cond

A sync.Cond lets goroutines wait until a condition on shared data becomes true. It is built on a mutex (L): Wait unlocks it, sleeps, and re-locks it when woken; Signal wakes one waiter and Broadcast wakes all. Always check the condition in a loop, because the state may have changed again by the time you run:

Go Waiting for a condition with Cond

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.

The program prints all 3 waiters released. If a waiter starts after ready is already true, the for loop skips Wait completely, so nobody can miss the signal. In most new code a channel (close(ch) as a broadcast) is simpler than Cond; Cond shines when many goroutines wait on a changing state, such as a bounded queue that is "not full" or "not empty".

sync.Map

sync.Map is a concurrent map that needs no extra locking. Its methods are Store, Load, LoadOrStore, LoadAndDelete, Delete, Range and a few more. It stores any for keys and values, so you lose type safety.

Go Using sync.Map

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.

The output is 1 true, 1 true, 3 false and total: 4. The official guidance is that sync.Map is only better than a plain map plus a Mutex in two cases: each key is written once and read many times (like a cache that only grows), or goroutines work on mostly disjoint sets of keys. For everything else, a typed map[K]V with a Mutex or RWMutex is clearer and often faster.

sync.Pool

A sync.Pool keeps a set of temporary objects for reuse, so you do not allocate and garbage-collect a new one every time. A typical use is a reusable buffer. Get returns a pooled item or calls New to make one; Put returns it:

Go Reusing buffers with a Pool

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.

The output is Hello, Ada! and Hello, Linus!. Two cautions: the pool may drop its items at any garbage collection, so never store anything in it that must survive, and always reset an object before reuse, because it still holds its old contents. Pools are an optimization to apply after measuring (performance tuning comes back to it).

Do not copy a lock

A Mutex, WaitGroup, Once and the others contain state. Copying one after use gives you a second, independent lock, which silently protects nothing. This happens easily with value receivers and with assignments:

Go
type Counter struct {
	mu sync.Mutex
	n  int
}

func (c Counter) Value() int { // BUG: value receiver copies the mutex
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.n
}

go vet reports it with a message like this (file and line numbers will differ):

TEXT
./main.go:10:9: Value passes lock by value: Counter contains sync.Mutex

The fix is a pointer receiver (func (c *Counter) Value() int), and passing structs that contain locks by pointer. Value versus pointer receivers explains the general rule, and a struct with a mutex field is one of the clearest cases for pointer receivers.

Lock granularity

How much data does one lock protect? A single lock around everything is simple but makes goroutines queue up. Many fine-grained locks allow more parallelism but are harder to get right. A middle path that works well is sharding: split a big map into several shards, each with its own lock, and pick the shard by hashing the key.

Go Sharded counters reduce lock contention

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.

The output is 3 1 2. Two goroutines working on keys in different shards no longer wait for each other. Add this complexity only after profiling shows lock contention; a plain mutex is fine for most programs.

Deadlocks

A deadlock is a situation where goroutines wait for each other forever. The most common mutex deadlocks are:

  1. Locking twice in the same goroutine. Go's mutexes are not reentrant: a goroutine that holds the lock and calls Lock again waits for itself.
  2. Lock-order inversion: goroutine A holds lock 1 and wants lock 2, while goroutine B holds lock 2 and wants lock 1. The cure is to always acquire multiple locks in the same global order.
  3. Forgetting to unlock on an early return (use defer).
Go Locking a Mutex twice (fails on purpose)

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.

The first line prints, then the runtime stops the program:

TEXT
first lock acquired
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [sync.Mutex.Lock]:

followed by a stack trace pointing at main.go:13, the second Lock. As with channel deadlocks, the runtime can only report it when every goroutine is stuck; in a bigger program the stuck goroutines would just hang quietly.

Whenever you can, avoid needing two locks at once. Prefer one lock per piece of data, keep critical sections free of calls into unknown code, and think about whether a channel-based design (one goroutine owns the data, others send it requests) would remove the shared state entirely. The atomics lesson covers a lock-free option for simple counters and flags.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the pattern mu.Lock(); defer mu.Unlock() appear so often?

    A deferred Unlock runs however the function exits, so the lock cannot be left held by accident.
  2. 2. What happens if a goroutine calls Lock on a sync.Mutex it already holds?

    Go mutexes are not reentrant. The second Lock waits for an Unlock that can never come, because the only goroutine that could call it is the one waiting.
  3. 3. When is sync.RWMutex a good choice over sync.Mutex?

    RWMutex lets many readers run at once. It has extra overhead, so it only pays off for read-heavy data with non-trivial critical sections.
  4. 4. What does the following print?

    o := sync.OnceValue(func() int { fmt.Print("x"); return 1 }); fmt.Print(o(), o())

    The wrapped function runs only on the first call and its result is cached, so x is printed once, followed by 1 and 1.
  5. 5. Why is a method with a value receiver, func (c Counter) Value() int, a bug when Counter contains a sync.Mutex?

    Each call copies the struct including the mutex state. go vet warns that the method passes a lock by value; use a pointer receiver.

Summary

  • Use a sync.Mutex to guard shared data: lock, defer unlock, keep the critical section short, and keep the mutex beside the data it protects.
  • Built-in maps are not safe for concurrent writes; wrap them in a struct with a mutex or use sync.Map for its special access patterns.
  • sync.RWMutex allows many concurrent readers or one writer; it helps only when reads dominate.
  • sync.Once (and OnceFunc, OnceValue, OnceValues) runs initialization exactly once, and all callers see the finished result.
  • sync.Cond waits for a state change; always re-check the condition in a loop. Often a closed channel is simpler.
  • sync.Pool recycles temporary objects to reduce garbage; reset them before reuse and never rely on items surviving.
  • Never copy a value that contains a lock (use pointer receivers); go vet finds this.
  • Mutexes are not reentrant. Avoid deadlocks by locking in one fixed order, never locking twice, and releasing with defer.

Next: Atomic Operations shows lock-free counters and flags with sync/atomic.