C++11 并发指南五(std::condition_variable 详解)
前面三讲《C++11 并发指南二(std::thread 详解)》,《C++11 并发指南三(std::mutex 详解)》分别介绍了 std::thread,std::mutex,std::future 等相关内容,相信读者对 C++11 中的多线程编程有了一个最基本的认识,本文将介绍 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[];
- // spawn 10 threads:
- for (int i = ; i < ; ++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 ;
- }
执行结果如下:
- concurrency ) ./ConditionVariable-basic1
- threads ready to race...
- thread
- thread
- thread
- thread
- thread
- thread
- thread
- thread
- thread
- thread
好了,对条件变量有了一个基本的了解之后,我们来看看 std::condition_variable 的各个成员函数。
std::condition_variable 构造函数
default (1) |
|
---|---|
copy [deleted] (2) |
|
std::condition_variable 的拷贝构造函数被禁用,只提供了默认构造函数。
std::condition_variable::wait() 介绍
unconditional (1) |
|
---|---|
predicate (2) |
|
std::condition_variable 提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex),不妨设获得锁 lck),直到另外某个线程调用 notify_* 唤醒了当前线程。
在线程被阻塞时,该函数会自动调用 lck.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。
另外,一旦当前线程获得通知(notified,通常是另外某个线程调用 notify_* 唤醒了当前线程),wait() 函数也是自动调用 lck.lock(),使得 lck 的状态和 wait 函数被调用时相同。
在第二种情况下(即设置了 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 = ;
- bool shipment_available()
- {
- return cargo != ;
- }
- // 消费者线程.
- void consume(int n)
- {
- for (int i = ; i < n; ++i) {
- std::unique_lock <std::mutex> lck(mtx);
- cv.wait(lck, shipment_available);
- std::cout << cargo << '\n';
- cargo = ;
- }
- }
- int main()
- {
- std::thread consumer_thread(consume, ); // 消费者线程.
- // 主线程为生产者线程, 生产 10 个物品.
- for (int i = ; i < ; ++i) {
- while (shipment_available())
- std::this_thread::yield();
- std::unique_lock <std::mutex> lck(mtx);
- cargo = i + ;
- cv.notify_one();
- }
- consumer_thread.join();
- return ;
- }
程序执行结果如下:
- concurrency ) ./ConditionVariable-wait
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 时才会被解除阻塞,因此相当于如下代码:
- return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));
请看下面的例子(参考),下面的例子中,主线程等待 th 线程输入一个值,然后将 th 线程从终端接收的值打印出来,在 th 线程接受到值之前,主线程一直等待,每个一秒超时一次,并打印一个 ".":
- #include <iostream> // std::cout
- #include <thread> // std::thread
- #include <chrono> // std::chrono::seconds
- #include <mutex> // std::mutex, std::unique_lock
- #include <condition_variable> // std::condition_variable, std::cv_status
- std::condition_variable cv;
- int value;
- void do_read_value()
- {
- std::cin >> value;
- cv.notify_one();
- }
- int main ()
- {
- std::cout << "Please, enter an integer (I'll be printing dots): \n";
- std::thread th(do_read_value);
- std::mutex mtx;
- std::unique_lock<std::mutex> lck(mtx);
- while (cv.wait_for(lck,std::chrono::seconds()) == std::cv_status::timeout) {
- std::cout << '.';
- std::cout.flush();
- }
- std::cout << "You entered: " << value << '\n';
- th.join();
- return ;
- }
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 时才会被解除阻塞,因此相当于如下代码:
- while (!pred())
- if ( wait_until(lck,abs_time) == cv_status::timeout)
- return pred();
- return 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 = ; // shared value by producers and consumers
- void consumer()
- {
- std::unique_lock < std::mutex > lck(mtx);
- while (cargo == )
- cv.wait(lck);
- std::cout << cargo << '\n';
- cargo = ;
- }
- void producer(int id)
- {
- std::unique_lock < std::mutex > lck(mtx);
- cargo = id;
- cv.notify_one();
- }
- int main()
- {
- std::thread consumers[], producers[];
- // spawn 10 consumers and 10 producers:
- for (int i = ; i < ; ++i) {
- consumers[i] = std::thread(consumer);
- producers[i] = std::thread(producer, i + );
- }
- // join them back:
- for (int i = ; i < ; ++i) {
- producers[i].join();
- consumers[i].join();
- }
- return ;
- }
std::condition_variable::notify_all() 介绍
唤醒所有的等待(wait)线程。如果当前没有等待线程,则该函数什么也不做。请看下面的例子:
- #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[];
- // spawn 10 threads:
- for (int i = ; i < ; ++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 ;
- }
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[];
- // spawn 10 threads:
- for (int i=; i<; ++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 ;
- }
好了,到此为止,<condition_variable> 头文件中的两个条件变量类(std::condition_variable 和 std::condition_variable_any)、枚举类型(std::cv_status)、以及辅助函数(std::notify_all_at_thread_exit())都已经介绍完了。从下一章开始我会逐步开始介绍 <atomic> 头文件中的内容,后续的文章还会介绍 C++11 的内存模型,涉及内容稍微底层一些,希望大家能够保持兴趣,学完 C++11 并发编程,如果你发现本文中的错误,也请给我反馈 ;-)。
C++11 并发指南五(std::condition_variable 详解)的更多相关文章
- C++11 并发指南五(std::condition_variable 详解)(转)
前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...
- 【转】C++11 并发指南五(std::condition_variable 详解)
http://www.cnblogs.com/haippy/p/3252041.html 前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三 ...
- 【C/C++开发】C++11 并发指南三(std::mutex 详解)
本系列文章主要介绍 C++11 并发编程,计划分为 9 章介绍 C++11 的并发和多线程编程,分别如下: C++11 并发指南一(C++11 多线程初探)(本章计划 1-2 篇,已完成 1 篇) C ...
- C++11 并发指南三(std::mutex 详解)
上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::thread 的一些用法,并给出了两个小例子,本文将介绍 std::mutex 的用法. Mutex ...
- C++11 并发指南三(std::mutex 详解)(转)
转自:http://www.cnblogs.com/haippy/p/3237213.html 上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::th ...
- C++11 并发指南二(std::thread 详解)
上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...
- C++11 并发指南二(std::thread 详解)(转)
上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...
- 【C/C++开发】C++11 并发指南二(std::thread 详解)
上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...
- C++11 并发指南六(atomic 类型详解三 std::atomic (续))
C++11 并发指南六( <atomic> 类型详解二 std::atomic ) 介绍了基本的原子类型 std::atomic 的用法,本节我会给大家介绍C++11 标准库中的 std: ...
随机推荐
- {Links}{Matting}{Saliency Detection}{Superpixel}Source links
自然图像抠图/视频抠像技术发展情况梳理(image matting, alpha matting, video matting)--计算机视觉专题1 http://blog.csdn.net/ansh ...
- 2016.02.02 JS事件
今天看完JS事件部分,所剩时间不多,务必分秒珍惜.
- 【原】JS正则表达式里的控制符
正则表达式易于使用而又让人费解,乍一看上去,就像是一行行的乱码,但是它的功能确实又不容小觑.今天整理正则时,纠正了自己的一个误解. 先缕一缕: 正则表达式的两种声明方式: 字面量.构造器 (RegEx ...
- VC++绘图时,利用双缓冲解决屏幕闪烁 转载
最近做中国象棋,绘制界面时遇到些问题,绘图过程中屏幕闪烁,估计都会想到利用双缓冲来解决问题,但查了下网上双缓冲的资料,发现基本是MFC的,转化为VC++后,大概代码如下: void DrawBmp(H ...
- 深入理解js——执行上下文
什么是"执行上下文"?暂且不下定义,先看一段代码: 第一句报错,a未定义,很正常.第二句.第三句输出都是undefined,说明浏览器在执行console.log(a)时,已经知道 ...
- 上传文件(单文件)(FormData)(前端代码+.NET服务器端)
由于样式需要不能直接用file,只能用文本框+按钮 <form class="form-horizontal form-bordered form-row-strippe" ...
- Ajax2
一.完整版Ajax $.ajax({ url: "Ashxs/Login.ashx", data: { "name": name, "pwd" ...
- 比较两个Long对象值
比较两个Long对象的值是否相等,不可以使用双等号进行比较,(long int Integer可以用双等号进行比较)可以采用如下方式: 1.使用equals方法进行比较 Long a=new Long ...
- C++队列中应该注意的一些问题
第一次在C++中写类,新手,见笑 #include<iostream.h>#include<iostream>template<typename T> class ...
- HttpModule的一些初步认识
新建一个类 ValidaterHttpModuleEvents继承管道接口 IHttpModule,代码如下 public class ValidaterHttpModuleEvents:IHttpM ...