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

















