Synchronization Primitives
Synchronization Primitives
A quick guide to mutexes, shared locks, semaphores, latches, barriers, and coordination patterns.
Synchronization Primitives
A quick guide to mutexes, shared locks, semaphores, latches, barriers, and coordination patterns.
std::mutex: exclusive lock.std::shared_mutex: many readers or one writer.std::condition_variable: wait for state changes.std::counting_semaphore: limit concurrent access to a pool.std::latch: one-shot rendezvous.std::barrier: repeated phase synchronization.std::shared_mutex mutex;
void read_value() {
std::shared_lock lock(mutex);
}
void write_value() {
std::unique_lock lock(mutex);
}
std::counting_semaphore<4> slots(4);
Use semaphores when access should be capped instead of fully serialized.
latch: workers finish setup before the next step begins.barrier: multiple threads repeat phased work together.