Thread Synchronization in C++: Condition Variable Correct Usage and Semaphore Comparison

2025-09-26

Let's dive into the common issues and look at some alternatives, like C++20's std::counting_semaphore.

A condition variable is used to block a thread until another thread notifies it that some condition has been met. It must always be used with a std::mutex to protect the shared data (the "condition") that the threads are waiting on.

Here is the standard, correct way to use a condition variable, often called the "producer-consumer" pattern

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <string>

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;

void worker_thread() {
    // 1. Acquire a unique_lock.
    std::unique_lock<std::mutex> lk(m); 
    
    // 2. Wait, releasing the lock until notified AND the predicate is true.
    // The wait function checks the predicate and will ONLY return 
    // when both notified AND the predicate is true.
    cv.wait(lk, []{ return ready; }); 

    // 3. The thread wakes up, and the lock 'lk' is re-acquired.
    std::cout << "Worker: Processing data: " << data << std::endl;
    
    // ... do work ...

    // 4. Release the lock before or after notify (before is often better for contention).
    // Lock 'lk' will be automatically released when it goes out of scope,
    // but explicit unlock before notify can sometimes improve performance.
}

void master_thread() {
    {
        std::lock_guard<std::mutex> lk(m); // Lock the shared data.
        data = "Ready to process!";         // Modify the shared data.
        ready = true;
        std::cout << "Master: Data is ready." << std::endl;
    } // Mutex is unlocked when lock_guard goes out of scope.

    // 5. Notify the waiting thread(s).
    cv.notify_one(); 
}

// int main() {
//     std::thread worker(worker_thread);
//     std::thread master(master_thread);
//     worker.join();
//     master.join();
// }

The two biggest mistakes developers make are related to missed notifications and spurious wakeups.

The most famous problem is the spurious wakeup. A thread waiting on a condition variable might occasionally wake up even if no other thread called notify_one() or notify_all(). This is a behavior allowed by the standard, often due to underlying OS thread library implementation details.

If the wait function doesn't check the condition (the predicate), the thread might wake up spuriously and execute its critical section even though the data isn't actually ready!

void worker_thread_wrong() {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk); //  DANGER! The thread might wake up spuriously.
    // The shared condition 'ready' is NOT checked here!
    
    if (ready) {
        std::cout << "Worker: Processing data: " << data << std::endl;
    } else {
        std::cout << "Worker: Woke up spuriously or condition is missed." << std::endl;
    }
}

The correct solution is to always wrap the wait in a loop or use the overloaded wait that takes a predicate (a lambda function). The predicate-version is concise and handles the loop for you.

void worker_thread_correct() {
    std::unique_lock<std::mutex> lk(m);
    
    // 1. Manual Loop:
    // while (!ready) { // Check the condition.
    //     cv.wait(lk); 
    // }
    
    // OR 2. Predicate Overload (Preferred):
    cv.wait(lk, []{ return ready; }); 
    
    // This ensures the thread is only unblocked when *both* notified *AND* the condition is true.
    // The predicate is checked *before* waiting, and *after* waking up (even spuriously).
}

If a thread calls notify_one() before the waiting thread has entered its wait() state, the notification is lost, and the waiting thread will block forever, even if the condition is already met.

In the following scenario, if master_thread runs before worker_thread reaches cv.wait(), the notification is lost.

// Imagine this sequence:
// 1. master_thread starts and sets ready=true.
// 2. master_thread calls notify_one(). (Notification is lost because no one is waiting).
// 3. worker_thread starts and calls cv.wait(lk, []{ return ready; }); 
//    Since 'ready' is already true, it thankfully won't block forever!

// However, if we didn't use the predicate:
void worker_thread_bad_wait() {
    std::unique_lock<std::mutex> lk(m);
    // If 'master_thread' ran first and notified, this will block forever:
    cv.wait(lk); //  Blocks forever if notification was missed! 
}

Using the predicate ([]{ return ready; }) is the robust solution because it checks the shared condition before calling wait. If the condition (ready) is already true, the thread won't wait at all, preventing the "lost wakeup" problem!

For simpler signaling tasks where you don't need to check a complex shared state, or you're managing resource count, C++20 introduced Semaphores (<semaphore>) as a great, often simpler alternative.

A std::binary_semaphore acts like a simple one-shot signal or a basic mutex, useful for ensuring one thread finishes a task before another starts, like a simple signal without explicit shared state checks.

Featurestd::condition_variablestd::binary_semaphore (C++20)
Primary UseWait on an arbitrary, complex boolean condition (state).Simple signaling or controlling access to one resource.
Required StateNeeds a std::mutex and a shared state variable (e.g., bool ready).Has an internal counter (0 or 1), no explicit shared state needed for basic use.
Wait/Signalwait() / notify_one()acquire() / release()

For a simple "wait for a signal" scenario, the semaphore simplifies the code because you don't need a mutex and a separate boolean flag.

#include <iostream>
#include <thread>
#include <semaphore> // C++20 header

// Initialized to 0 (non-signaled state, so acquire() will block)
std::binary_semaphore sync_point(0); 
std::string data = "Initial"; 

void worker_thread_sem() {
    sync_point.acquire(); // Blocks until counter > 0, then decrements it.

    // No need for a separate lock or boolean check here for this simple task!
    std::cout << "Worker: Processing data: " << data << std::endl;
}

void master_thread_sem() {
    data = "Ready for semaphore processing!"; // Data access still needs careful management 
                                             // if not atomic or protected, but the *signaling* is simpler.
    
    std::cout << "Master: Signaling completion." << std::endl;
    sync_point.release(); // Increments the counter (to 1), waking the worker.
}

// int main() {
//     std::thread worker(worker_thread_sem);
//     std::thread master(master_thread_sem);
//     worker.join();
//     master.join();
// }

cpp



Common Pitfalls of std::cauchy_distribution::param and How to Fix Them

The param member function in the C++ standard library's numerics header is used to get or set the parameters of a Cauchy distribution


A Guide to Decrementing C++ time_point Objects Effectively

This operator is used to decrement a time_point object by one tick. A tick is the smallest unit of time supported by the clock associated with the time_point


Troubleshooting std::is_literal_type in C++

In C++, a literal type is a class or type that can be used in constant expressions. This means you can create variables of that type whose values are known at compile time



C++ Localization: Safer Alternatives to setlocale(LC_ALL)

While LC_ALL might seem convenient, it can lead to some common pitfalls. Let's break down the problems and explore some better alternatives


C++ memory_resource: Pitfalls, Solutions, and Alternatives Explained

First, a quick refresher. The memory_resource library, introduced in C++17, provides a way to separate a C++ container's storage policy from its type


C++ multimap: A Guide to equal_range

The std::multimap::count method is straightforward it returns the number of elements with a specific key. This is useful


A Friendly Guide to C++ std::unordered_set::extract: Troubleshooting & Alternatives

The extract function lets you "extract" a node from a container. Think of it like carefully plucking a single item from a bag without disrupting the other items


Using std::stack::empty Correctly in C++

The std::stack::empty function is a member function of the C++ Standard Library container std::stack. Its sole purpose is to check if a stack is empty


C++ Stream Positioning: Common seekp Troubles and Solutions

A lot of the issues people run into with seekp have to do with how streams work. Here are a couple of the most common ones and how to fix them


C++ Dynamic Memory Management: A Guide to std::pmr::unsynchronized_pool_resource

First off, what is std::pmr::unsynchronized_pool_resource? It's a memory resource from the C++ PMR (Polymorphic Memory Resource) library