命名空间
变体
操作

std::condition_variable::notify_one

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

如果有任何线程正在等待 *this,调用 notify_one 将解除阻塞其中一个等待的线程。

目录

[编辑] 参数

(无)

[编辑] 返回值

(无)

[编辑] 注意

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

通知线程不需要持有与等待线程所持有的互斥量相同的锁;事实上,这样做是一种性能倒退,因为被通知的线程会立即再次阻塞,等待通知线程释放锁。然而,某些实现(特别是许多 pthreads 的实现)会识别这种情况,并通过在通知调用中将等待线程从条件变量的队列直接转移到互斥量的队列来避免这种“赶上并等待”的场景,而无需唤醒它。

然而,当需要精确调度事件时,在持有锁的情况下进行通知可能是必要的,例如,如果条件满足时等待线程会退出程序,导致通知线程的条件变量被销毁。在互斥量解锁但通知之前发生虚假唤醒将导致在已销毁的对象上调用通知。

[编辑] 示例

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
 
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;
 
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cout << "Waiting... \n";
    cv.wait(lk, []{ return i == 1; });
    std::cout << "...finished waiting; i == " << i << '\n';
    done = true;
}
 
void signals()
{
    std::this_thread::sleep_for(200ms);
    std::cout << "Notifying falsely...\n";
    cv.notify_one(); // waiting thread is notified with i == 0.
                     // cv.wait wakes up, checks i, and goes back to waiting
 
    std::unique_lock<std::mutex> lk(cv_m);
    i = 1;
    while (!done) 
    {
        std::cout << "Notifying true change...\n";
        lk.unlock();
        cv.notify_one(); // waiting thread is notified with i == 1, cv.wait returns
        std::this_thread::sleep_for(300ms);
        lk.lock();
    }
}
 
int main()
{
    std::thread t1(waits), t2(signals);
    t1.join(); 
    t2.join();
}

可能的输出

Waiting... 
Notifying falsely...
Notifying true change...
...finished waiting; i == 1

[编辑] 参阅

通知所有等待线程
(公共成员函数) [编辑]
C 文档 for cnd_signal