命名空间
变体
操作

std::condition_variable_any::notify_all

来自 cppreference.cn
 
 
并发支持库
线程
(C++11)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
协作取消
互斥
(C++11)
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
闩锁和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
Hazard 指针
原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(在 C++20 中弃用)
(C++11)(在 C++20 中弃用)
内存顺序
(C++11)(在 C++26 中弃用)
原子操作的自由函数
原子标志的自由函数
 
 
void notify_all() noexcept;
(since C++11)

解除当前正在等待 *this 的所有线程的阻塞。

目录

[edit] 参数

(none)

[edit] 返回值

(none)

[edit] 注意

notify_one()/notify_all() 的效果和 wait()/wait_for()/wait_until() 的三个原子部分(解锁+等待、唤醒和锁定)发生在单一的总顺序中,可以被视为原子变量的修改顺序:该顺序特定于此单独的条件变量。这使得 notify_one() 不可能例如被延迟并解除在调用 notify_one() 之后才开始等待的线程的阻塞。

通知线程不需要持有与等待线程所持有的互斥锁相同的锁。 这样做可能是一种悲观化,因为被通知的线程会立即再次阻塞,等待通知线程释放锁,尽管某些实现识别出这种模式,并且不尝试唤醒在锁下被通知的线程。

[edit] 示例

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
 
std::condition_variable_any cv;
std::mutex cv_m; // This mutex is used for three purposes:
                 // 1) to synchronize accesses to i
                 // 2) to synchronize accesses to std::cerr
                 // 3) for the condition variable cv
int i = 0;
 
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{ return i == 1; });
    std::cerr << "...finished waiting. i == 1\n";
}
 
void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        std::cerr << "Notifying...\n";
    }
    cv.notify_all();
 
    std::this_thread::sleep_for(std::chrono::seconds(1));
 
    {
        std::lock_guard<std::mutex> lk(cv_m);
        i = 1;
        std::cerr << "Notifying again...\n";
    }
    cv.notify_all();
}
 
int main()
{
    std::thread t1(waits), t2(waits), t3(waits), t4(signals);
    t1.join(); 
    t2.join(); 
    t3.join();
    t4.join();
}

可能的输出

Waiting...
Waiting...
Waiting...
Notifying...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

[edit] 参见

通知一个等待线程
(public member function) [edit]
C 文档 for cnd_broadcast