(转 )C++11多线程条件变量std::condition_variable详解
目录
std::condition_variable::wait()
std::condition_variable::wait_for()
std::condition_variable::wait_until()
std::condition_variable::notify_one()
std::condition_variable::notify_all()
std::notify_all_at_thread_exit
前言
本文转载来源:https://www.cnblogs.com/wangshaowei/p/9593201.html.
本文将介绍 C++11 标准中 <condition_variable> 头文件里面的类和相关函数。 <condition_variable > 头文件主要包含了与条件变量相关的类和函数。
相关的类包括 :
- std::condition_variable
- std::condition_variable_any
还有枚举类型:
- std::cv_status。
另外还包括函数:
- std::notify_all_at_thread_exit()
下 面分别介绍一下以上几种类型。
std::condition_variable 类介绍
std::condition_variable 是条件变量,更多有关条件变量的定义参考维基百科。Linux 下使用 Pthread 库中的 pthread_cond_*() 函数提供了与条件变量相关的功能, Windows 则参考 MSDN。
当 std::condition_variable 对象的某个 wait 函数被调用的时候,它使用 std::unique_lock(通过 std::mutex) 来锁住当前线程。当前线程会一直被阻塞,直到另外一个线程在相同的 std::condition_variable 对象上调用了 notification 函数来唤醒当前线程。
std::condition_variable 对象通常使用 std::unique_lock<std::mutex> 来等待,如果需要使用另外的 lockable 类型,可以使用 std::condition_variable_any 类,本文后面会讲到 std::condition_variable_any 的用法。
首先我们来看一个简单的例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量.
bool ready = false; // 全局标志位.
void do_print_id(int id)
{
std::unique_lock <std::mutex> lck(mtx);
while (!ready) // 如果标志位不为 true, 则等待...
cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
// 线程被唤醒, 继续往下执行打印线程编号id.
std::cout << "thread " << id << '\n';
}
void go()
{
std::unique_lock <std::mutex> lck(mtx);
ready = true; // 设置全局标志位为 true.
cv.notify_all(); // 唤醒所有线程.
}
int main()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(do_print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto & th:threads)
th.join();
return 0;
}
执行结果如下:
0 threads ready to race...
thread 1
thread 0
thread 2
thread 3
thread 4
thread 5
thread 6
thread 7
thread 8
thread 9
好了,对条件变量有了一个基本的了解之后,我们来看看 std::condition_variable 的各个成员函数。
std::condition_variable 构造函数
default (1) | |
---|---|
copy [deleted] (2) | |
std::condition_variable::wait()
unconditional (1) | |
---|---|
predicate (2) | |
std::condition_variable 提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex),不妨设获得锁 lck),直到另外某个线程调用 notify_* 唤醒了当前线程,该函数会自动调用 lck.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。
在第二种情况下(即设置了 Predicate),只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞。因此第二种情况类似以下代码:
while (!pred())
wait(lck);
看下面例子(参考):
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
int cargo = 0;
bool shipment_available()
{
return cargo != 0;
}
// 消费者线程.
void consume(int n)
{
for (int i = 0; i < n; ++i) {
std::unique_lock <std::mutex> lck(mtx);
cv.wait(lck, shipment_available);
std::cout << cargo << '\n';
cargo = 0;
}
}
int main()
{
std::thread consumer_thread(consume, 10); // 消费者线程.
// 主线程为生产者线程, 生产 10 个物品.
for (int i = 0; i < 10; ++i) {
while (shipment_available())
std::this_thread::yield();
std::unique_lock <std::mutex> lck(mtx);
cargo = i + 1;
cv.notify_one();
}
consumer_thread.join();
return 0;
}
程序执行结果如下:
concurrency ) ./ConditionVariable-wait
1
2
3
4
5
6
7
8
9
10
std::condition_variable::wait_for()
unconditional (1) | |
---|---|
predicate (2) | |
与 std::condition_variable::wait() 类似,不过 wait_for 可以指定一个时间段,在当前线程收到通知或者指定的时间 rel_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_for 返回,剩下的处理步骤和 wait() 类似。
另外,wait_for 的重载版本(predicte(2))的最后一个参数 pred 表示 wait_for 的预测条件,只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞。
std::condition_variable::wait_until()
unconditional (1) | |
---|---|
predicate (2) | |
与 std::condition_variable::wait_for 类似,但是 wait_until 可以指定一个时间点,在当前线程收到通知或者指定的时间点 abs_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_until 返回,剩下的处理步骤和 wait_until() 类似。
另外,wait_until 的重载版本(predicte(2))的最后一个参数 pred 表示 wait_until 的预测条件,只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞。
std::condition_variable::notify_one()
唤醒某个等待(wait)线程。如果当前没有等待线程,则该函数什么也不做,如果同时存在多个等待线程,则唤醒某个线程是不确定的(unspecified)。
请看下例(参考):
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
int cargo = 0; // shared value by producers and consumers
void consumer()
{
std::unique_lock < std::mutex > lck(mtx);
while (cargo == 0)
cv.wait(lck);
std::cout << cargo << '\n';
cargo = 0;
}
void producer(int id)
{
std::unique_lock < std::mutex > lck(mtx);
cargo = id;
cv.notify_one();
}
int main()
{
std::thread consumers[10], producers[10];
// spawn 10 consumers and 10 producers:
for (int i = 0; i < 10; ++i) {
consumers[i] = std::thread(consumer);
producers[i] = std::thread(producer, i + 1);
}
// join them back:
for (int i = 0; i < 10; ++i) {
producers[i].join();
consumers[i].join();
}
return 0;
}
std::condition_variable::notify_all()
唤醒所有的等待(wait)线程。如果当前没有等待线程,则该函数什么也不做。
std::condition_variable_any()
与 std::condition_variable 类似,只不过 std::condition_variable_any 的 wait 函数可以接受任何 lockable 参数,而 std::condition_variable 只能接受 std::unique_lock<std::mutex> 类型的参数,除此以外,和 std::condition_variable 几乎完全一样。
std::cv_status 枚举类型
cv_status::no_timeout | wait_for 或者 wait_until 没有超时,即在规定的时间段内线程收到了通知。 |
cv_status::timeout | wait_for 或者 wait_until 超时。 |
std::notify_all_at_thread_exit
函数原型为:
void notify_all_at_thread_exit (condition_variable& cond, unique_lock<mutex> lck);
当调用该函数的线程退出时,所有在 cond 条件变量上等待的线程都会收到通知。请看下例(参考):
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
std::notify_all_at_thread_exit(cv,std::move(lck));
ready = true;
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);
std::cout << "10 threads ready to race...\n";
std::thread(go).detach(); // go!
for (auto& th : threads) th.join();
return 0;
}
好了,到此为止,<condition_variable> 头文件中的两个条件变量类(std::condition_variable 和 std::condition_variable_any)、枚举类型(std::cv_status)、以及辅助函数(std::notify_all_at_thread_exit())都已经介绍完了。
以下 参考:https://blog.youkuaiyun.com/weixin_41374099/article/details/88324141
lambda表达式
这是一种闭包,是内嵌函数。基本格式是:
auto a = [ ] { } ;
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
void test01() {
//简单的lambda
auto basicLambda = [] {cout << "hello,world!" << endl; };
basicLambda();
//指明返回类型
auto add = [](int a, int b)->int {return a + b; };
//自动推断返回类型
auto multiply = [](int a, int b) {return a * b; };
cout << "2 + 5 = " << add(2, 5) << "\n2 X 5 = " << multiply(2, 5);
//泛型lambda
auto add_2 = [](auto x, auto y) {return x + y; };
cout <<"\n" <<add_2(2.5, 3.5) << endl;
}
void test02() {//捕捉
int x = 10;
//mutable保证捕捉的变量(复制捕捉)可修改
auto add_x = [x](int a) mutable { x *= 2; return a + x; };//复制捕捉x
//引用捕捉的可以随便修改
auto multiply_x = [&x](int a) { x *= 2; return a * x; };//引用捕捉x
cout << "add_x(10) = " << add_x(10) << "\nmultiply_x(10) = " << multiply_x(10) << endl;
}
void test03() {
auto a = [] {cout << "A" << endl; };
auto b = [] {cout << "B" << endl; };
//a = b;非法,lambda无法赋值,毕竟lambda禁用了赋值操作符
auto c = a;///合法,会生成一股副本,毕竟没有禁用拷贝构造函数
}
}
void main() {
test01();
//test02();
system("pause");
}
————————————————
版权声明:本文为优快云博主「化简派蒙」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_41374099/article/details/88324141
( )内写传递的变量
mutable (任何情况下,变量可修改的标识符)写在花括号前 mutable { } ;
[ ] 内需要写捕捉的东西:
- [ ]:默认不捕获任何变量;
- [=]:默认以值捕获所有变量;
- [&]:默认以引用捕获所有变量;
- [x]:仅以值捕获x,其它变量不捕获;
- [&x]:仅以引用捕获x,其它变量不捕获;
- [=, &x]:默认以值捕获所有变量,但是x是例外,通过引用捕获;
- [&, x]:默认以引用捕获所有变量,但是x是例外,通过值捕获;
- [this]:通过引用捕获当前对象(其实是复制指针);
- [*this]:通过传值方式捕获当前对象;