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
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
Advanced
9 steps
go
func (h *ArticleHandler) Create(c *gin.Context) { var req struct { Title string `json:"title" binding:"required"` Body string `json:"body" binding:"required"`
Handling a POST request in Gin
request binding
validation
http status codes
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.