std::condition_variable
来自cppreference.com
![]() |
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <condition_variable> 中定义
|
||
class condition_variable; |
(since C++11) | |
。
condition_variable
类是原始的,可以用来阻塞一个线程或多个线程在同一时间同步,直到。原文:
The
condition_variable
class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until:- 。从另一个线程收到通知。原文:a notification is received from another thread
- 。 一个超时过期或者。
- 。 。虚假唤醒。发生。
。任何线程等待std::condition_variable
,首先获得一个std::unique_lock。等待原子操作释放互斥体的线程暂停执行。条件变量的通知时,该线程被唤醒,重新获取互斥体.原文:Any thread that intends to wait onstd::condition_variable
has to acquire a std::unique_lock first. The wait operations atomically release the mutex and suspend the execution of the thread. When the condition variable is notified, the thread is awakened, and the mutex is reacquired.。类std::condition_variable
是一个StandardLayoutType
。它不是CopyConstructible
,MoveConstructible
,CopyAssignable
,MoveAssignable
.原文:The classstd::condition_variable
is aStandardLayoutType
. It is notCopyConstructible
,MoveConstructible
,CopyAssignable
,MoveAssignable
.目录
[编辑] 。会员类型。
。会员类型。Definition native_handle_type
。 “实现自定义”。[编辑] 。成员函数。
构造对象
(公共成员函数)解构的对象
(公共成员函数)operator=[删除]</div></div>不可复制的转让
(公共成员函数)。通知。通知一个正在等待的线程
(公共成员函数)通知所有等待的线程
(公共成员函数)。 等待。的条件变量阻塞当前线程,直到被唤醒原文:blocks the current thread until the condition variable is woken up
(公共成员函数)的条件变量阻塞当前线程,直到被唤醒或在指定的超时时间原文:blocks the current thread until the condition variable is woken up or after the specified timeout duration
(公共成员函数)阻止当前线程,直到条件变量被唤醒,或直至已经达到指定的时间点原文:blocks the current thread until the condition variable is woken up or until specified time point has been reached
(公共成员函数)。本机手柄。返回的本地手柄
(公共成员函数)[编辑] 。为例。
#include <condition_variable> #include <mutex> #include <thread> #include <iostream> #include <queue> #include <chrono> int main() { std::queue<int> produced_nums; std::mutex m; std::condition_variable cond_var; bool done = false; bool notified = false; std::thread producer([&]() { for (int i = 0; i < 5; ++i) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::unique_lock<std::mutex> lock(m); std::cout << "producing " << i << '\n'; produced_nums.push(i); notified = true; cond_var.notify_one(); } done = true; cond_var.notify_one(); }); std::thread consumer([&]() { std::unique_lock<std::mutex> lock(m); while (!done) { while (!notified) { // loop to avoid spurious wakeups cond_var.wait(lock); } while (!produced_nums.empty()) { std::cout << "consuming " << produced_nums.front() << '\n'; produced_nums.pop(); } notified = false; } }); producer.join(); consumer.join(); }
Possible output:
producing 0 consuming 0 producing 1 consuming 1 producing 2 consuming 2 producing 3 consuming 3 producing 4 consuming 4
-