Once in a while, I come across a bit of short, readable, well-documented and explained source code that's delightful to read and teaches me something new. Today, I found once such example, in Go's sync
package, for sync.Once
. Here's a snippet, though you should read the whole (very short) file:
func (o *Once) Do(f func()) {
// Note: Here is an incorrect implementation of Do:
//
// if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
// f()
// }
//
// Do guarantees that when it returns, f has finished.
// This implementation would not implement that guarantee:
// given two simultaneous calls, the winner of the cas would
// call f, and the second would return immediately, without
// waiting for the first's call to f to complete.
// This is why the slow path falls back to a mutex, and why
// the atomic.StoreUint32 must be delayed until after f returns.
if atomic.LoadUint32(&o.done) == 0 {
// Outlined slow-path to allow inlining of the fast-path.
o.doSlow(f)
}
}
Quick lessons about the Go compiler's inlining rules, how to use atomic intrinsics, and all in clean, well-explained code. Lovely.