Using sync.RWMutex
Go offers another type of mutex, called sync.RWMutex, that allows multiple readers to hold the lock but only a single writer - sync.RWMutex is an extension of sync.Mutex that adds two methods named sync.RLock and sync.RUnlock, which are used for locking and unlocking for reading purposes. Locking and unlocking a sync.RWMutex for exclusive writing should be done with Lock() and Unlock(), respectively.
This means that either one writer can hold the lock or multiple readers: not both! You will most likely use such a mutex when most of the goroutines want to read a variable and you do not want goroutines to wait in order to get an exclusive lock.
In order to demystify sync.RWMutex a little, you should discover that the sync.RWMutex ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access