std::condition_variable
来自 cppreference.cn
定义于头文件 <condition_variable> |
||
class condition_variable; |
(since C++11) | |
std::condition_variable
是一个同步原语,与 std::mutex 一起使用,以阻塞一个或多个线程,直到另一个线程修改共享变量(条件)并通知 std::condition_variable
。
打算修改共享变量的线程必须
- 获取 std::mutex (通常通过 std::lock_guard)。
- 在拥有锁时修改共享变量。
- 在
std::condition_variable
上调用 notify_one 或 notify_all (可以在释放锁之后完成)。
即使共享变量是原子的,也必须在拥有互斥锁时修改它,才能正确地将修改发布到等待线程。
任何打算在 std::condition_variable
上等待的线程必须
- 在用于保护共享变量的互斥锁上获取 std::unique_lock<std::mutex>。
- 执行以下操作之一
- 检查条件,以防它已经被更新和通知。
- 在
std::condition_variable
上调用 wait、wait_for 或 wait_until (原子地释放互斥锁并暂停线程执行,直到条件变量被通知、超时到期或发生伪唤醒,然后在返回之前原子地获取互斥锁)。 - 检查条件,如果未满足则继续等待。
- 或
- 使用 wait、wait_for 和 wait_until 的谓词重载,它执行相同的三个步骤。
std::condition_variable
仅与 std::unique_lock<std::mutex> 一起工作,这允许在某些平台上实现最大效率。std::condition_variable_any 提供了一个条件变量,它可以与任何 BasicLockable 对象一起工作,例如 std::shared_lock。
条件变量允许并发调用 wait、wait_for、wait_until、notify_one 和 notify_all 成员函数。
类 std::condition_variable
是一个 StandardLayoutType。它不是 CopyConstructible、MoveConstructible、CopyAssignable 或 MoveAssignable。
目录 |
[edit] 嵌套类型
名称 | 定义 |
native_handle_type
|
实现定义 |
[edit] 成员函数
构造对象 (公共成员函数) | |
析构对象 (公共成员函数) | |
operator= [已删除] |
不可复制赋值 (公共成员函数) |
通知 | |
通知一个等待线程 (公共成员函数) | |
通知所有等待线程 (公共成员函数) | |
等待 | |
阻塞当前线程,直到条件变量被唤醒 (公共成员函数) | |
阻塞当前线程,直到条件变量被唤醒或超过指定的超时时长 (公共成员函数) | |
阻塞当前线程,直到条件变量被唤醒或到达指定时间点 (公共成员函数) | |
原生句柄 | |
返回原生句柄 (公共成员函数) |
[edit] 示例
std::condition_variable
与 std::mutex 结合使用,以促进线程间通信。
运行此代码
#include <condition_variable> #include <iostream> #include <mutex> #include <string> #include <thread> std::mutex m; std::condition_variable cv; std::string data; bool ready = false; bool processed = false; void worker_thread() { // wait until main() sends data std::unique_lock lk(m); cv.wait(lk, []{ return ready; }); // after the wait, we own the lock std::cout << "Worker thread is processing data\n"; data += " after processing"; // send data back to main() processed = true; std::cout << "Worker thread signals data processing completed\n"; // manual unlocking is done before notifying, to avoid waking up // the waiting thread only to block again (see notify_one for details) lk.unlock(); cv.notify_one(); } int main() { std::thread worker(worker_thread); data = "Example data"; // send data to the worker thread { std::lock_guard lk(m); ready = true; std::cout << "main() signals data ready for processing\n"; } cv.notify_one(); // wait for the worker { std::unique_lock lk(m); cv.wait(lk, []{ return processed; }); } std::cout << "Back in main(), data = " << data << '\n'; worker.join(); }
输出
main() signals data ready for processing Worker thread is processing data Worker thread signals data processing completed Back in main(), data = Example data after processing
[edit] 参见
(C++11) |
提供与任何锁类型关联的条件变量 (类) |
(C++11) |
提供基本互斥设施 (类) |
(C++11) |
实现严格基于作用域的互斥锁所有权包装器 (类模板) |
(C++11) |
实现可移动的互斥锁所有权包装器 (类模板) |