Documentation
¶
Overview ¶
rwmutex demonstrates when to use multiple readers, single writer lock.
The sync.Mutex is often used for exclusive locks during reads and writes. Let's say we have so many read operations, but only have few writes. Since the exclusive locks are acquired by read operations, writer are slower. In such case, the sync.RWMutex is useful. This has the method RLock() which can used to allow multiple read operations at the same without using exclusive locks. This also has the usual Lock() method intended to be used for write operations with exclusive locks.
Ensure that RLock() is used only for read-only blocks and no writes involved. Because even some read-only like functions might update something like a counter in shared variable. If in doubt use exclusive locks
RWMutex involves more bookkeeping and slower than normal Mutex. So it is only profitable to use with more readers than writers.