Essential Go Mutex  Suggest an edit

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: * a writer lock takes exclusive lock * a reader lock will allow another readers but not writer

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 {
	v, isCached := cache[n]
	if isCached {
		return v

	v = expensiveOperation(n)

	cache[n] = v
	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()
total: 30
total: 30
Read-Write mutes (RWMutex)
Mutex gotchas
Detecting races
  ↑ ↓ to navigate     ↵ to select     Esc to close