Essential Go Mutex  Edit on GitHub      File Issue

Read-Write mutes (RWMutex)

In a sync.Mutex Lock() always takes an exclusive lock.

In read-heavy scenarios we can improve performance if we allow multiple readers but only one writer.

A sync.RWMutex has 2 types of lock function: lock for reading and lock for writing.

It follows the following rules:

Here’s a cache variant that uses read-write lock:

var cache map[int]int
var mu sync.RWMutex

func expensiveOperation(n int) int {
	// in real code this operation would be very expensive
	return n * n
}

func getCached(n int) int {
	mu.RLock()
	v, isCached := cache[n]
	mu.RUnlock()
	if isCached {
		return v
	}

	v = expensiveOperation(n)

	mu.Lock()
	cache[n] = v
	mu.Unlock()
	return v
}

func accessCache() {
	total := 0
	for i := 0; i < 5; i++ {
		n := getCached(i)
		total += n
	}
	fmt.Printf("total: %d\n", total)
}

cache = make(map[int]int)
go accessCache()
accessCache()
total: 30
total: 30
Mutex/
Read-Write mutes (RWMutex)
Mutex gotchas
Detecting races
  ↑ ↓ to navigate     ↵ to select     Esc to close