Sync
Go sync.Once is Simple... Does It Really?
The sync.Once is probably the easiest sync primitive to use, but there’s more under the hood than you might think. It’s also a good opportunity to understand how it works by juggling both atomic operations and mutexes.
Go sync.Map: The Right Tool for the Right Job
Go’s sync.Map isn’t a magic bullet for all concurrent map needs. It’s got some good tricks up its sleeve, like handling reads without locking, but it’s not always the best choice. This article dives into how sync.Map works under the hood, from its two-map system to the bottom line of expunged entries.
Go Singleflight Melts in Your Code, Not in Your DB
What singleflight does is ensure that only one of those goroutines actually runs the operation, like getting the data from the database. It allows only one ‘in-flight’ (ongoing) operation for the same piece of data (known as a ‘key’) at any given moment.
Go sync.Cond, the Most Overlooked Sync Mechanism
In Go, sync.Cond is a synchronization primitive, though it’s not as commonly used as its siblings like sync.Mutex or sync.WaitGroup. That said, as a Go engineer, you don’t really want to find yourself reading through code that uses sync.Cond and not have a clue what’s going on.
Go sync.WaitGroup and The Alignment Problem
When we’re spinning off many goroutines to do their thing, we want to keep track of them so that the main goroutine doesn’t just finish up and exit before everyone else is done. That’s where the WaitGroup comes in. Each time one of our goroutines wraps up its task, it lets the WaitGroup know.
Go sync.Pool and the Mechanics Behind It
Instead of just throwing these objects after each use, which would only give the garbage collector more work, we stash them in a pool (sync.Pool
). The next time we need something similar, we just grab it from the pool instead of making a new one from scratch.
Go sync.Mutex: Normal and Starvation Mode
Mutex in Go has two main flows: Lock and Unlock and 2 modes: Normal and Starvation Mode. The state field of mutex is a 32-bit integer that represents the current state, it’s divided into multiple bits that encode various pieces of information about the mutex.