std::atomic_wait 与 std::atomic_notify ​

什么是 atomic wait/notify ​

C++20 为 std::atomic 和 std::atomic_flag 添加了等待/通知机制,定义在 <atomic> 头文件中。这让原子变量可以像条件变量一样用于线程间的等待和唤醒,但不需要配合 mutex。

  • wait(old):如果原子变量的值等于 old,则阻塞当前线程,直到被 notify 唤醒
  • notify_one():唤醒一个在 wait 的线程
  • notify_all():唤醒所有在 wait 的线程
cpp
#include <atomic>

std::atomic<int> flag{0};

// 线程A:等待 flag 变为非零
flag.wait(0);  // 阻塞,直到 flag != 0 且被 notify

// 线程B:修改 flag 并唤醒
flag.store(1);
flag.notify_one();  // 唤醒一个等待的线程

wait/notify vs 条件变量 ​

特性atomic wait/notifycondition_variable
需要 mutex不需要需要
等待条件值相等判断任意谓词
代码复杂度简单较复杂
适用范围简单状态变化复杂条件
虚假唤醒可能发生可能发生
性能通常更好(无锁)有锁开销

基本示例 ​

cpp
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
#include <mutex>
#include <string>
#include <chrono>

std::mutex cout_mutex;

void safe_print(const std::string& msg) {
    std::lock_guard<std::mutex> lock(cout_mutex);
    std::cout << msg << std::endl;
}

// ============================
// 示例1:基本的等待和通知
// ============================

void basic_demo() {
    std::atomic<int> ready{0};

    std::jthread worker([&ready] {
        safe_print("  工作线程: 等待启动信号...");
        ready.wait(0);  // 等待 ready 变为非0

        safe_print("  工作线程: 收到信号,开始工作");
        // 做工作...
        safe_print("  工作线程: 工作完成");
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    safe_print("主线程: 发送启动信号");

    ready.store(1);       // 修改值
    ready.notify_one();   // 唤醒等待的线程
}

// ============================
// 示例2:notify_all 唤醒多个线程
// ============================

void notify_all_demo() {
    std::atomic<int> gate{0};

    std::vector<std::jthread> threads;
    for (int i = 0; i < 5; i++) {
        threads.emplace_back([&gate, i] {
            safe_print("  线程 " + std::to_string(i) + " 等待开门...");
            gate.wait(0);  // 所有线程等待

            safe_print("  线程 " + std::to_string(i) + " 通过");
        });
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    safe_print("主线程: 开门!");

    gate.store(1);
    gate.notify_all();  // 唤醒所有等待的线程
}

// ============================
// 示例3:多状态等待
// ============================

void multi_state_demo() {
    std::atomic<int> state{0};
    // 0: 初始, 1: 数据准备好, 2: 处理完成

    std::jthread producer([&state] {
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        safe_print("  生产者: 数据准备完毕");
        state.store(1);
        state.notify_all();

        // 等待消费者处理完
        state.wait(1);
        safe_print("  生产者: 消费者已处理完毕");
    });

    std::jthread consumer([&state] {
        // 等待数据准备好
        state.wait(0);
        safe_print("  消费者: 收到数据,处理中...");

        std::this_thread::sleep_for(std::chrono::milliseconds(50));

        safe_print("  消费者: 处理完成");
        state.store(2);
        state.notify_all();
    });
}

// ============================
// 示例4:atomic_flag 的 wait/notify
// ============================

void atomic_flag_demo() {
    std::atomic_flag flag = ATOMIC_FLAG_INIT;  // 初始为 false

    std::jthread waiter([&flag] {
        safe_print("  等待方: 等待 flag 被设置...");
        flag.wait(false);  // 等待 flag 变为 true

        safe_print("  等待方: flag 已设置!");
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    safe_print("主线程: 设置 flag");
    flag.test_and_set();   // 设置为 true
    flag.notify_one();     // 唤醒等待的线程
}

// ============================
// 示例5:自旋等待 vs wait
// ============================

void spin_vs_wait_demo() {
    std::atomic<bool> ready{false};

    // 方式1:自旋等待(浪费 CPU)
    // while (!ready.load()) { /* 空循环 */ }

    // 方式2:atomic wait(不浪费 CPU)
    std::jthread worker([&ready] {
        safe_print("  工作线程: 使用 wait(不浪费 CPU)");
        ready.wait(false);  // 高效等待,不消耗 CPU
        safe_print("  工作线程: 被唤醒");
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    ready.store(true);
    ready.notify_one();
}

// ============================
// 示例6:简单的事件循环
// ============================

void event_loop_demo() {
    std::atomic<int> event{0};
    // 0: 无事件, 1: 事件A, 2: 事件B, 3: 退出

    std::jthread handler([&event] {
        while (true) {
            event.wait(0);  // 等待事件发生

            int e = event.load();
            switch (e) {
                case 1:
                    safe_print("  处理事件 A");
                    break;
                case 2:
                    safe_print("  处理事件 B");
                    break;
                case 3:
                    safe_print("  收到退出信号");
                    return;
            }

            // 重置为等待状态
            event.store(0);
        }
    });

    // 发送事件
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    event.store(1);
    event.notify_one();

    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    event.store(2);
    event.notify_one();

    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    event.store(3);
    event.notify_one();
}

// ============================
// 示例7:非成员函数版本
// ============================

void free_function_demo() {
    std::atomic<int> value{0};

    std::jthread worker([&value] {
        // 使用非成员函数版本
        std::atomic_wait(&value, 0);
        safe_print("  被唤醒,值: " + std::to_string(value.load()));
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    value.store(42);
    std::atomic_notify_one(&value);  // 非成员函数版本
}

// ============================
// 示例8:配合 compare_exchange 使用
// ============================

void cas_notify_demo() {
    std::atomic<int> counter{0};
    constexpr int target = 5;

    // 等待 counter 达到目标值
    std::jthread waiter([&counter] {
        while (counter.load() < target) {
            int current = counter.load();
            counter.wait(current);  // 等待值变化
        }
        safe_print("  目标达成! counter = " + std::to_string(counter.load()));
    });

    // 逐步递增 counter
    for (int i = 0; i < target; i++) {
        std::this_thread::sleep_for(std::chrono::milliseconds(30));
        counter.fetch_add(1);
        counter.notify_all();  // 每次修改都通知
        safe_print("  counter = " + std::to_string(counter.load()));
    }
}

int main() {
    std::cout << "=== 基本等待通知 ===" << std::endl;
    basic_demo();

    std::cout << "\n=== notify_all ===" << std::endl;
    notify_all_demo();

    std::cout << "\n=== 多状态 ===" << std::endl;
    multi_state_demo();

    std::cout << "\n=== atomic_flag ===" << std::endl;
    atomic_flag_demo();

    std::cout << "\n=== wait vs 自旋 ===" << std::endl;
    spin_vs_wait_demo();

    std::cout << "\n=== 事件循环 ===" << std::endl;
    event_loop_demo();

    std::cout << "\n=== 非成员函数 ===" << std::endl;
    free_function_demo();

    std::cout << "\n=== CAS + notify ===" << std::endl;
    cas_notify_demo();

    return 0;
}

成员函数和非成员函数对照 ​

成员函数非成员函数说明
a.wait(old)std::atomic_wait(&a, old)等待值变化
a.wait(old, order)std::atomic_wait_explicit(&a, old, order)带内存序的等待
a.notify_one()std::atomic_notify_one(&a)唤醒一个线程
a.notify_all()std::atomic_notify_all(&a)唤醒所有线程

适用场景 ​

  • 简单的线程间信号通知(替代条件变量)
  • 状态机中等待状态变化
  • 替代自旋等待(节省 CPU)
  • 轻量级事件通知
  • 不想引入 mutex 的简单同步

常见问题 ​

wait 会不会虚假唤醒?

可能。wait 被唤醒后会重新检查值是否仍然等于 old,如果仍然相等会继续等待。但实现可能有虚假唤醒。建议在循环中使用 wait。

wait 之前必须先修改值再 notify 吗?

是的。wait 检查的是值是否等于 old。如果不先修改值,即使 notify 了,wait 发现值没变也会继续等待。

notify 时没有线程在 wait 会怎样?

什么也不会发生。notify 不会被"记住"——如果之后有线程调用 wait,它不会因为之前的 notify 而立即返回。

所有原子类型都支持 wait/notify 吗?

是的。所有 std::atomic<T> 特化和 std::atomic_flag 都支持 wait/notify。

注意事项 ​

  • 先修改值再 notify,否则 wait 检查值不变会继续等待
  • wait 可能虚假唤醒,建议在循环中使用
  • notify 不会被缓存——如果没有线程在 wait,通知会丢失
  • wait 比自旋等待高效——不会持续占用 CPU
  • notify_one 只唤醒一个线程,notify_all 唤醒所有
  • 对于复杂条件,仍然建议使用 condition_variable

总结 ​

C++20 为原子变量添加了 wait/notify 机制,让原子变量可以用于线程间的高效等待和唤醒。wait(old) 在值等于 old 时阻塞线程(不消耗 CPU),notify_one/notify_all 唤醒等待的线程。与条件变量相比,atomic wait/notify 不需要 mutex,代码更简洁,对于简单的状态变化等待是更轻量的选择。使用时注意先修改值再 notify,并在循环中调用 wait 来处理虚假唤醒。