第 18.19.4 節

condition_variable

0瀏覽次數0訪問次數--跳出率--平均停留

What problem does this section solve?

std::condition_variable is used for "one thread waits on a condition variable, and another thread changes the condition and notifies."

A typical example is the producer-consumer pattern: producers put data into a queue, consumers wait when there is no data, and are woken up once data becomes available.

Condition variables are usually used with std::unique_lock<std::mutex> because wait() need to temporarily release the lock while waiting and reacquire it once woken up.

Example code

Example 1: Producer-Consumer

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>

std::queue<int> data_queue;
// 加锁用来保护共享数据,避免多个线程同时修改造成数据竞争。
std::mutex queue_mutex;
std::condition_variable queue_cv;
bool finished = false;

void producer()
{
    for (int value = 1; value <= 3; ++value)
    {
        {
            std::lock_guard<std::mutex> lock(queue_mutex);
            data_queue.push(value);
            std::cout << "produced " << value << "\n";
        }

        queue_cv.notify_one();
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }

    {
        std::lock_guard<std::mutex> lock(queue_mutex);
        finished = true;
    }
    queue_cv.notify_one();
}

void consumer()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        queue_cv.wait(lock, [] {
            return !data_queue.empty() || finished;
        });

        while (!data_queue.empty())
        {
            int value = data_queue.front();
            data_queue.pop();

            lock.unlock();
            std::cout << "consumed " << value << "\n";
            lock.lock();
        }

        if (finished)
        {
            break;
        }
    }
}

int main()
{
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。
    // 创建子线程,让这部分代码和 main 线程并发运行。
    std::thread p(producer);
    std::thread c(consumer);

    // join 会等待子线程结束,避免 main 提前退出。
    p.join();
    c.join();

    std::cout << "all done\n";

    return 0;
}

One possible outcome

produced 1
consumed 1
produced 2
consumed 2
produced 3
consumed 3
all done

queue_cv.wait(lock, 条件) is crucial. After a thread is awakened, it rechecks the condition to avoid logic errors caused by spurious wakeups.

Example 2: Wait for one notification

If it's just one thread waiting for another thread to prepare data, a condition variable can also be used. This example is shorter than producer-consumer and is suitable for first understanding the cooperation between wait and notify_one.

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

// 加锁用来保护共享数据,避免多个线程同时修改造成数据竞争。
std::mutex data_mutex;
std::condition_variable data_cv;
std::string message;
bool ready = false;

void prepare()
{
    {
        std::lock_guard<std::mutex> lock(data_mutex);
        message = "hello from worker";
        ready = true;
    }

    data_cv.notify_one();
}

int main()
{
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。
    // 创建子线程,让这部分代码和 main 线程并发运行。
    std::thread worker(prepare);

    std::unique_lock<std::mutex> lock(data_mutex);
    data_cv.wait(lock, [] {
        return ready;
    });

    std::cout << message << "\n";

    lock.unlock();
    // join 会等待子线程结束,避免 main 提前退出。
    worker.join();

    return 0;
}

Results

hello from worker

Common Errors

  1. wait() Not using condition predicates and relying only on a single wakeup can easily be affected by spurious wakeups.
  2. After modifying the sharing conditions, you forgot notify_one() or notify_all().
  3. Performing time-consuming operations while holding the lock, preventing other threads from progressing in a timely manner.
  4. The condition variables, mutexes, and shared conditions are not managed within a unified logical framework.

Summary

  • condition_variable is used for inter-thread waiting and notification.
  • wait() typically needs to be used in conjunction with unique_lock.
  • Recommended to write cv.wait(lock, [] { return 条件; });.
  • After modifying the conditions, call notify_one() or notify_all().
  • Condition variables are suitable for scenarios such as producer-consumer models, task queues, and waiting for initialization completion.
音乐页