User Tools

Site Tools


go:concurrency:rwmutex

sync.RWMutex

What is it?

`sync.RWMutex` is a read/write mutual exclusion lock. It allows multiple readers at the same time, but only one writer (and writers exclude readers).

What is it used for?

  • Protect shared data that is read very often but written less frequently.
  • Improve throughput compared to `Mutex` in read-heavy workloads.

When to use

  • Many goroutines read shared state, and updates are relatively rare.
  • You can clearly separate “read” vs “write” sections.

Example

package main
 
import "sync"
 
type Store struct {
    mu sync.RWMutex
    m  map[string]string
}
 
func (s *Store) Get(k string) (string, bool) {
    s.mu.RLock()
    defer s.mu.RUnlock()
    v, ok := s.m[k]
    return v, ok
}
 
func (s *Store) Set(k, v string) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.m[k] = v
}

Notes / pitfalls

  • Use `RLock/RUnlock` for read-only sections; use `Lock/Unlock` for writes.
  • Avoid “lock upgrade” patterns (RLock then Lock) — can cause deadlocks if done wrong.
  • If writes are frequent, `RWMutex` may not be faster than `Mutex`.

Hard words (English)

  • read-heavy /ˈriːd ˈhevi/: đọc nhiều (ít ghi)
  • throughput /ˈθruːpʊt/: thông lượng
  • exclude /ɪkˈskluːd/: loại trừ, chặn
  • deadlock /ˈdedlɑːk/: kẹt khóa
go/concurrency/rwmutex.txt · Last modified: by phong2018