Read-Write mutes (RWMutex)

suggest change

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 {
	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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents