http://www.cnblogs.com/haippy/p/3252041.html

前面三讲《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 的用法。

首先我们来看一个简单的例子

  1. #include <iostream> // std::cout
  2. #include <thread> // std::thread
  3. #include <mutex> // std::mutex, std::unique_lock
  4. #include <condition_variable> // std::condition_variable
  5.  
  6. std::mutex mtx; // 全局互斥锁.
  7. std::condition_variable cv; // 全局条件变量.
  8. bool ready = false; // 全局标志位.
  9.  
  10. void do_print_id(int id)
  11. {
  12. std::unique_lock <std::mutex> lck(mtx);
  13. while (!ready) // 如果标志位不为 true, 则等待...
  14. cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
  15. // 线程被唤醒, 继续往下执行打印线程编号id.
  16. std::cout << "thread " << id << '\n';
  17. }
  18.  
  19. void go()
  20. {
  21. std::unique_lock <std::mutex> lck(mtx);
  22. ready = true; // 设置全局标志位为 true.
  23. cv.notify_all(); // 唤醒所有线程.
  24. }
  25.  
  26. int main()
  27. {
  28. std::thread threads[10];
  29. // spawn 10 threads:
  30. for (int i = 0; i < 10; ++i)
  31. threads[i] = std::thread(do_print_id, i);
  32.  
  33. std::cout << "10 threads ready to race...\n";
  34. go(); // go!
  35.  
  36. for (auto & th:threads)
  37. th.join();
  38.  
  39. return 0;
  40. }

执行结果如下:

  1. concurrency ) ./ConditionVariable-basic1
  2. 10 threads ready to race...
  3. thread 1
  4. thread 0
  5. thread 2
  6. thread 3
  7. thread 4
  8. thread 5
  9. thread 6
  10. thread 7
  11. thread 8
  12. thread 9

好了,对条件变量有了一个基本的了解之后,我们来看看 std::condition_variable 的各个成员函数。

std::condition_variable 构造函数

default (1)
  1. condition_variable();
copy [deleted] (2)
  1. condition_variable (const condition_variable&) = delete;

std::condition_variable 的拷贝构造函数被禁用,只提供了默认构造函数。

std::condition_variable::wait() 介绍

unconditional (1)
  1. void wait (unique_lock<mutex>& lck);
predicate (2)
  1. template <class Predicate>
  2. void wait (unique_lock<mutex>& lck, Predicate pred);

std::condition_variable 提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex),不妨设获得锁 lck),直到另外某个线程调用 notify_* 唤醒了当前线程。

在线程被阻塞时,该函数会自动调用 lck.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。另外,一旦当前线程获得通知(notified,通常是另外某个线程调用 notify_* 唤醒了当前线程),wait() 函数也是自动调用 lck.lock(),使得 lck 的状态和 wait 函数被调用时相同。

在第二种情况下(即设置了 Predicate),只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞。因此第二种情况类似以下代码:

  1. while (!pred()) wait(lck);

请看下面例子(参考):

  1. #include <iostream> // std::cout
  2. #include <thread> // std::thread, std::this_thread::yield
  3. #include <mutex> // std::mutex, std::unique_lock
  4. #include <condition_variable> // std::condition_variable
  5.  
  6. std::mutex mtx;
  7. std::condition_variable cv;
  8.  
  9. int cargo = 0;
  10. bool shipment_available()
  11. {
  12. return cargo != 0;
  13. }
  14.  
  15. // 消费者线程.
  16. void consume(int n)
  17. {
  18. for (int i = 0; i < n; ++i) {
  19. std::unique_lock <std::mutex> lck(mtx);
  20. cv.wait(lck, shipment_available);
  21. std::cout << cargo << '\n';
  22. cargo = 0;
  23. }
  24. }
  25.  
  26. int main()
  27. {
  28. std::thread consumer_thread(consume, 10); // 消费者线程.
  29.  
  30. // 主线程为生产者线程, 生产 10 个物品.
  31. for (int i = 0; i < 10; ++i) {
  32. while (shipment_available())
  33. std::this_thread::yield();
  34. std::unique_lock <std::mutex> lck(mtx);
  35. cargo = i + 1;
  36. cv.notify_one();
  37. }
  38.  
  39. consumer_thread.join();
  40.  
  41. return 0;
  42. }

程序执行结果如下:

  1. concurrency ) ./ConditionVariable-wait
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. 6
  8. 7
  9. 8
  10. 9
  11. 10

std::condition_variable::wait_for() 介绍

unconditional (1)
  1. template <class Rep, class Period>
  2. cv_status wait_for (unique_lock<mutex>& lck,
  3. const chrono::duration<Rep,Period>& rel_time);
predicate (2)
  1. template <class Rep, class Period, class Predicate>
  2. bool wait_for (unique_lock<mutex>& lck,
  3. const chrono::duration<Rep,Period>& rel_time, Predicate pred);

与 std::condition_variable::wait() 类似,不过 wait_for 可以指定一个时间段,在当前线程收到通知或者指定的时间 rel_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_for 返回,剩下的处理步骤和 wait() 类似。

另外,wait_for 的重载版本(predicte(2))的最后一个参数 pred 表示 wait_for 的预测条件,只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞,因此相当于如下代码:

  1. return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));

请看下面的例子(参考),下面的例子中,主线程等待 th 线程输入一个值,然后将 th 线程从终端接收的值打印出来,在 th 线程接受到值之前,主线程一直等待,每个一秒超时一次,并打印一个 ".":

  1. #include <iostream> // std::cout
  2. #include <thread> // std::thread
  3. #include <chrono> // std::chrono::seconds
  4. #include <mutex> // std::mutex, std::unique_lock
  5. #include <condition_variable> // std::condition_variable, std::cv_status
  6.  
  7. std::condition_variable cv;
  8.  
  9. int value;
  10.  
  11. void do_read_value()
  12. {
  13. std::cin >> value;
  14. cv.notify_one();
  15. }
  16.  
  17. int main ()
  18. {
  19. std::cout << "Please, enter an integer (I'll be printing dots): \n";
  20. std::thread th(do_read_value);
  21.  
  22. std::mutex mtx;
  23. std::unique_lock<std::mutex> lck(mtx);
  24. while (cv.wait_for(lck,std::chrono::seconds(1)) == std::cv_status::timeout) {
  25. std::cout << '.';
  26. std::cout.flush();
  27. }
  28.  
  29. std::cout << "You entered: " << value << '\n';
  30.  
  31. th.join();
  32. return 0;
  33. }

std::condition_variable::wait_until 介绍

unconditional (1)
  1. template <class Clock, class Duration>
  2. cv_status wait_until (unique_lock<mutex>& lck,
  3. const chrono::time_point<Clock,Duration>& abs_time);
predicate (2)
  1. template <class Clock, class Duration, class Predicate>
  2. bool wait_until (unique_lock<mutex>& lck,
  3. const chrono::time_point<Clock,Duration>& abs_time,
  4. Predicate pred);

与 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 时才会被解除阻塞,因此相当于如下代码:

  1. while (!pred())
  2. if ( wait_until(lck,abs_time) == cv_status::timeout)
  3. return pred();
  4. return true;

std::condition_variable::notify_one() 介绍

唤醒某个等待(wait)线程。如果当前没有等待线程,则该函数什么也不做,如果同时存在多个等待线程,则唤醒某个线程是不确定的(unspecified)。

请看下例(参考):

  1. #include <iostream> // std::cout
  2. #include <thread> // std::thread
  3. #include <mutex> // std::mutex, std::unique_lock
  4. #include <condition_variable> // std::condition_variable
  5.  
  6. std::mutex mtx;
  7. std::condition_variable cv;
  8.  
  9. int cargo = 0; // shared value by producers and consumers
  10.  
  11. void consumer()
  12. {
  13. std::unique_lock < std::mutex > lck(mtx);
  14. while (cargo == 0)
  15. cv.wait(lck);
  16. std::cout << cargo << '\n';
  17. cargo = 0;
  18. }
  19.  
  20. void producer(int id)
  21. {
  22. std::unique_lock < std::mutex > lck(mtx);
  23. cargo = id;
  24. cv.notify_one();
  25. }
  26.  
  27. int main()
  28. {
  29. std::thread consumers[10], producers[10];
  30.  
  31. // spawn 10 consumers and 10 producers:
  32. for (int i = 0; i < 10; ++i) {
  33. consumers[i] = std::thread(consumer);
  34. producers[i] = std::thread(producer, i + 1);
  35. }
  36.  
  37. // join them back:
  38. for (int i = 0; i < 10; ++i) {
  39. producers[i].join();
  40. consumers[i].join();
  41. }
  42.  
  43. return 0;
  44. }

std::condition_variable::notify_all() 介绍

唤醒所有的等待(wait)线程。如果当前没有等待线程,则该函数什么也不做。请看下面的例子:

  1. #include <iostream> // std::cout
  2. #include <thread> // std::thread
  3. #include <mutex> // std::mutex, std::unique_lock
  4. #include <condition_variable> // std::condition_variable
  5.  
  6. std::mutex mtx; // 全局互斥锁.
  7. std::condition_variable cv; // 全局条件变量.
  8. bool ready = false; // 全局标志位.
  9.  
  10. void do_print_id(int id)
  11. {
  12. std::unique_lock <std::mutex> lck(mtx);
  13. while (!ready) // 如果标志位不为 true, 则等待...
  14. cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
  15. // 线程被唤醒, 继续往下执行打印线程编号id.
  16. std::cout << "thread " << id << '\n';
  17. }
  18.  
  19. void go()
  20. {
  21. std::unique_lock <std::mutex> lck(mtx);
  22. ready = true; // 设置全局标志位为 true.
  23. cv.notify_all(); // 唤醒所有线程.
  24. }
  25.  
  26. int main()
  27. {
  28. std::thread threads[10];
  29. // spawn 10 threads:
  30. for (int i = 0; i < 10; ++i)
  31. threads[i] = std::thread(do_print_id, i);
  32.  
  33. std::cout << "10 threads ready to race...\n";
  34. go(); // go!
  35.  
  36. for (auto & th:threads)
  37. th.join();
  38.  
  39. return 0;
  40. }

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

函数原型为:

  1. void notify_all_at_thread_exit (condition_variable& cond, unique_lock<mutex> lck);

当调用该函数的线程退出时,所有在 cond 条件变量上等待的线程都会收到通知。请看下例(参考):

  1. #include <iostream> // std::cout
  2. #include <thread> // std::thread
  3. #include <mutex> // std::mutex, std::unique_lock
  4. #include <condition_variable> // std::condition_variable
  5.  
  6. std::mutex mtx;
  7. std::condition_variable cv;
  8. bool ready = false;
  9.  
  10. void print_id (int id) {
  11. std::unique_lock<std::mutex> lck(mtx);
  12. while (!ready) cv.wait(lck);
  13. // ...
  14. std::cout << "thread " << id << '\n';
  15. }
  16.  
  17. void go() {
  18. std::unique_lock<std::mutex> lck(mtx);
  19. std::notify_all_at_thread_exit(cv,std::move(lck));
  20. ready = true;
  21. }
  22.  
  23. int main ()
  24. {
  25. std::thread threads[10];
  26. // spawn 10 threads:
  27. for (int i=0; i<10; ++i)
  28. threads[i] = std::thread(print_id,i);
  29. std::cout << "10 threads ready to race...\n";
  30.  
  31. std::thread(go).detach(); // go!
  32.  
  33. for (auto& th : threads) th.join();
  34.  
  35. return 0;
  36. }

好了,到此为止,<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 详解)的更多相关文章

  1. C++11 并发指南五(std::condition_variable 详解)

    前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...

  2. C++11 并发指南五(std::condition_variable 详解)(转)

    前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...

  3. 【C/C++开发】C++11 并发指南三(std::mutex 详解)

    本系列文章主要介绍 C++11 并发编程,计划分为 9 章介绍 C++11 的并发和多线程编程,分别如下: C++11 并发指南一(C++11 多线程初探)(本章计划 1-2 篇,已完成 1 篇) C ...

  4. C++11 并发指南三(std::mutex 详解)

    上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::thread 的一些用法,并给出了两个小例子,本文将介绍 std::mutex 的用法. Mutex ...

  5. C++11 并发指南三(std::mutex 详解)(转)

    转自:http://www.cnblogs.com/haippy/p/3237213.html 上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::th ...

  6. C++11 并发指南二(std::thread 详解)

    上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...

  7. C++11 并发指南二(std::thread 详解)(转)

    上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...

  8. 【C/C++开发】C++11 并发指南二(std::thread 详解)

    上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...

  9. C++11 并发指南六(atomic 类型详解三 std::atomic (续))

    C++11 并发指南六( <atomic> 类型详解二 std::atomic ) 介绍了基本的原子类型 std::atomic 的用法,本节我会给大家介绍C++11 标准库中的 std: ...

随机推荐

  1. 不安装谷歌市场,下载谷歌市场中的APK

    不安装谷歌市场,下载谷歌市场中的APK GooglePlayStore 是谷歌官方的的应用市场,有的时候还是需要从谷歌市场下载APK文件.国内的安卓手机厂商都不自带GooglePlay,甚至一些手机& ...

  2. Fiddler代理配置

     1.下载安装软件Fiddler 2.Fiddler设置HTTPS代理(如果代理的是https请求的需要操作这一步) 打开Fiddler,菜单栏:Tools -> Fiddler Options ...

  3. Dcloud课程6 php脚本如何在Linux下定时更新数据

    Dcloud课程6 php脚本如何在Linux下定时更新数据 一.总结 一句话总结:linux下用crontab命令实现定时任务. 1.linux下执行php脚本用什么命令? 直接用php命令php ...

  4. HTTP网络协议(一)

    1.了解Web及网络基础 TCP/IP协议族按层次可以分为下面四层: 应用层:决定了向用户提供应用服务时通信的活动,TCP/IP协议族内预存了各类通用的应用服务,比如:FTP(文件传输协议)和DNS( ...

  5. 如何把别人的原理图和pcb图建立一个完整的工程

    这里是我从网友那里下载的pcb图和原理图 我们怎么通过这两个文件建立一个完整的工程 我们选中pcb图文件,通过下面的操作,就可以导出pcb封装库: 同样的方法,我选中pcb图,然后用下面图的方法,就可 ...

  6. 软件——python,主函数

    1;; 如何在spyder中运行python程序 如下图,   写入一个输出  ' hellow word '的程序 然后点击运行按钮就可以运行了.

  7. Javascript和jquery事件--双击事件

    在js中和jq中对应的命名都为dblclick,ondblclick,但是ondblclick和dom元素的属性相似,可以在行内设置,也可以使用attr设置. 同时,双击事件需要关注一个问题,那就是双 ...

  8. (转)ORA-00257归档日志写满的解决方法

    转自:http://www.cnblogs.com/xwdreamer/p/3804509.html 背景: 在前一篇博客中我们提到了如何启动或关闭oracle的归档(ARCHIVELOG)模式,在我 ...

  9. POJ 2886 Who Gets the Most Candies?(线段树&#183;约瑟夫环)

    题意  n个人顺时针围成一圈玩约瑟夫游戏  每一个人手上有一个数val[i]   開始第k个人出队  若val[k] < 0 下一个出队的为在剩余的人中向右数 -val[k]个人   val[k ...

  10. numpy 高阶函数 —— np.histogram

    np.diff(a, n=1, axis=-1):n 表示差分的阶数: >> x = np.array([1, 2, 4, 7, 0]) >> np.diff(x) array ...