go
46 lines · 6 steps
Mutex vs RWMutex in Go
When reads vastly outnumber writes, an RWMutex lets readers run concurrently instead of serializing every access.
Explained by
highlit
1package main
2
3import "sync"
4
5// Counter uses a plain Mutex: every operation, read or write,
6// takes the same exclusive lock.
7type Counter struct {
8 mu sync.Mutex
9 count int
10}
11
12func (c *Counter) Inc() {
13 c.mu.Lock()
14 c.count++
15 c.mu.Unlock()
16}
17
18func (c *Counter) Value() int {
19 c.mu.Lock()
20 defer c.mu.Unlock()
21 return c.count
22}
23
24// Cache uses an RWMutex: many readers can hold RLock concurrently,
25// while writers take the exclusive Lock and block everyone.
26type Cache struct {
27 mu sync.RWMutex
28 data map[string]int
29}
30
31func NewCache() *Cache {
32 return &Cache{data: make(map[string]int)}
33}
34
35func (c *Cache) Get(key string) (int, bool) {
36 c.mu.RLock()
37 defer c.mu.RUnlock()
38 v, ok := c.data[key]
39 return v, ok
40}
41
42func (c *Cache) Set(key string, val int) {
43 c.mu.Lock()
44 defer c.mu.Unlock()
45 c.data[key] = val
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A plain Mutex serializes everything; even concurrent reads wait for one another.
- 2An RWMutex allows many simultaneous readers but gives writers exclusive access, blocking all readers.
- 3Reach for RWMutex only in read-heavy workloads, since its bookkeeping costs more than a plain Mutex under contention-light or write-heavy use.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/mutex-vs-rwmutex-in-go-explained-go-bd57/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.