Synchronization Constructs in the Go Standard Library
Go provides sync.Mutex as its implementation of a mutual exclusion lock. However, it is not the only synchronization construct that is a part of the standard library.
This blog post will look at four synchronization constructs that we can use instead of a sync.Mutex.
Counter

You may often see code using a sync.Mutex to synchronize access to a counter variable from multiple goroutines.
Like this:
| |
Instead of this, you can use an atomic.Int32 or atomic.Int64:
| |
Map

To synchronize a map, you will see code that uses a sync.Mutex or sync.RWMutex.
You gain some benefits using a sync.RWMutex with read-heavy operations on the map.
| |
Instead of using a map-mutex pair, you can use sync.Map:
| |
If you feel uneasy about the use of any in all sync.Map functions, you could define a generic wrapper:
| |
And then use the wrapper instead:
| |
One caveat is that the Range function is different from holding a lock around the range loop in the sync.RWMutex example. Range does not necessarily correspond to any consistent snapshot of the map’s contents.
Once Function

If you have a function called from multiple places in the code but you want it to run exactly once, you can do something like this:
| |
Or, better, you can use sync.Once:
| |
If your function is meant to return one or two values, you can use sync.OnceValue or sync.OnceValues.
Condition

Let’s say you want to make several goroutines wait for a condition to be met. You can, but shouldn’t, use a sync.Mutex for it:
| |
This code is very taxing on the CPU.
The standard library has sync.Cond for this:
| |
Unlike the example using sync.Mutex, this code is not taxing on the CPU. Wait returns for all goroutines only when Broadcast is called.
However, in a simple case like this, where you will signal only when the condition has been met, you can close a channel to signal to multiple goroutine:
| |
Note that in the case of using a channel to signal the goroutines you cannot reopen the channels. This approach works if you expect the condition to meet and not be changed anymore.
This post is 76th of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.
comments powered by Disqus