liveBook · Manning

Locking

As explained in Go by Example

Locking is a synchronization technique that restricts concurrent access to shared resources or protected operations.

Locking protects shared state when multiple goroutines may use it at once. A mutex acts as a gatekeeper: one goroutine receives exclusive access while others wait, preventing races that can otherwise cause stale writes, crashes, or data corruption. A mutex begins unlocked; Lock acquires exclusive access and Unlock lets a waiting goroutine proceed. section 8.2.4

Use a mutex around the resource whose operations must not overlap, not around unrelated work. For straightforward shared-state protection, mutexes are simpler and generally more efficient than routing state changes through channels, which primarily coordinate goroutines and add synchronization overhead. section 8.2.4 section 8.10

A practical locking pattern is:

  • Store a sync.RWMutex alongside the shared map in the owning type. section 8.2.4
  • Use Lock before changing the map, and defer Unlock immediately so every return path releases exclusive access. section 8.2.4 section 8.10
  • Use RLock and defer RUnlock for lookups when concurrent reads may proceed but writes must remain exclusive. section 8.2.4

Protecting an in-memory link service

A Shortener shared by HTTP handlers stores links in a map. Since requests run in separate goroutines, Shorten takes the write lock before checking, initializing, and saving a link. Resolve takes a read lock before retrieving one. This keeps the service safe for concurrent use while allowing multiple readers. section 8.2.4 section 8.2

Figure 8.5 Multiple goroutines using the same state may cause race conditions. A mutex gives them safe, orderly access to the shared state.
A diagram of a computer system

AI-generated content may be incorrect.

Compare unsynchronized concurrent map access with mutex-guarded access that orders operations and prevents stale writes. section 8.2.4

How Go by Example covers it

How deep it goes
Explains mutex locking behavior and develops RWMutex read/write protection with deferred release.
Examples
Uses a Shortener service whose Shorten and Resolve methods guard an in-memory link map.
What it assumes
Builds from a shared map and goroutines, introducing classical mutexes as race-condition protection.
What you can do after
Apply it via sync.RWMutex to make shared map access safe for concurrent goroutines.
How it connects
Connects mutexes with goroutines, race conditions, channels, maps, defer, and HTTP handlers.

Also explained in

Compare how 18 books explain locking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.