Table of Contents

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?

When to use

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

Hard words (English)