sync.RWMutex: Many Readers, One Writer
A lot of data in real apps is read often but rarely changed, like the price list of an online store. With a plain sync.Mutex, even two readers have to take turns, even though reading at the same time is perfectly safe as long as nobody is writing.
sync.RWMutex has two kinds of lock:
| Method | For | Behavior |
|---|---|---|
RLock / RUnlock | reading | Many goroutines can hold the read lock at the same time. |
Lock / Unlock | writing | Only one writer, and no readers while it holds the lock. |
type Kurs struct {
mu sync.RWMutex
nilai map[string]float64
}
func (k *Kurs) Ambil(kode string) float64 {
k.mu.RLock()
defer k.mu.RUnlock()
return k.nilai[kode]
}
func (k *Kurs) Perbarui(kode string, v float64) {
k.mu.Lock()
defer k.mu.Unlock()
k.nilai[kode] = v
}
Maps and goroutines
Maps in Go are not safe for concurrent use. If one goroutine writes to a map while another reads or writes it, the Go runtime stops the program with fatal error: concurrent map writes (or concurrent map read and map write). That's why a map shared between goroutines is almost always wrapped in a mutex.
When should you pick RWMutex?
- Use
RWMutexwhen reads far outnumber writes and the critical section isn't trivially short. - When in doubt, start with a plain
sync.Mutex.RWMutexcosts a bit more and isn't always faster. - Don't call
Lockwhile still holdingRLockin the same goroutine. That's a deadlock.
Task
Complete Katalog, an online store's product price list that thousands of visitors read and an admin updates now and then. The KatalogBaru constructor is already provided.
func (k *Katalog) SetHarga(nama string, harga int)stores or updates a price. Use the write lock.func (k *Katalog) Harga(nama string) (int, bool)returns the price andtrueif the product exists, or0, falseif it doesn't. Use the read lock.func (k *Katalog) Jumlah() intreturns how many products are in the catalog. Use the read lock.
The tests run dozens of writers and hundreds of readers at the same time.