liveBook · Manning

Locking

As explained in Go in Action, Second Edition

A lock is a synchronization mechanism that restricts concurrent access to a protected resource.

Locking coordinates concurrent access to shared data. Without it, goroutines can race, producing corrupted data, inconsistent results, and difficult-to-reproduce bugs. Go’s sync package provides Mutex and RWMutex for protecting critical sections. section 9.2.3

Choose the lock operation according to the access pattern:

  • Use Mutex with Lock and Unlock when modifying shared resources; only one goroutine enters the protected region. section 9.2.3
  • Use RWMutex with RLock and RUnlock for read-only operations, allowing concurrent readers while excluding writers. section 9.2.3
  • Keep locking straightforward, protect shared data consistently, and prefer channels when communication can avoid shared memory. section 9.6.1

A concurrent article store

An ArticleStore can combine an RWMutex, a cache, and a sorted article slice. AddArticles acquires a write lock before checking for duplicates, updating the cache, appending articles, and sorting. GetRecent acquires a read lock while selecting recent entries. Multiple feed-fetching goroutines can then add results safely, while the main goroutine retrieves the five most recent articles after a WaitGroup completes. section 9.2.3

How Go in Action, Second Edition covers it

How deep it goes
Explains race conditions, exclusive and read locks, and an ArticleStore implementation, while deferring broader synchronization internals.
Examples
Demonstrates an ArticleStore, RSS feed fetchers, duplicate filtering, sorted results, read locks, write locks, and WaitGroup coordination.
What it assumes
Assumes familiarity with goroutines and shared data while reinforcing race conditions and synchronization choices.
What you can do after
Apply it via sync.Mutex or sync.RWMutex to protect shared data and maintain consistency across concurrent operations.
How it connects
Connects mutexes with goroutines, channels, race conditions, critical sections, WaitGroup, and context.Context.

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 in Action, Second Edition. The section links point to the parts of the book it draws on.