#include <condition_variable>
#include <mutex>
#include <future>
#include <iostream>
#include <thread>
#include <queue>
using namespace std; queue<int> q;
mutex queueMutex;
condition_variable queueCondVar; void provider(int val)
{
for (int i = ; i < ; ++i)
{
{
this_thread::sleep_for(chrono::milliseconds());
cout << "\nWait\n";
this_thread::sleep_for(chrono::milliseconds());
lock_guard<mutex> lg(queueMutex);
q.push(val + i);
}
queueCondVar.notify_one();
//this_thread::sleep_for(chrono::milliseconds(val));
}
} void consumer(int num)
{
while (true)
{
int val;
{
unique_lock<mutex> ul(queueMutex);
queueCondVar.wait(ul, []{return !q.empty(); });
val = q.front();
q.pop();
}
cout << "consumer" << num << ":" << val << endl;
}
} int main()
{
auto p1 = async(launch::async, provider, );
auto p2 = async(launch::async, provider, );
auto p3 = async(launch::async, provider, ); auto c1 = async(launch::async, consumer, ); //this_thread::sleep_for(chrono::milliseconds(5000));
auto c2 = async(launch::async, consumer, ); //system("pause");
p1.get();
p2.get();
p3.get();
c1.get();
c2.get();
return ;
}

在consumer中:我们要使用

unique_lock<mutex> ul(queueMutex);
queueCondVar.wait(ul, []{return !q.empty(); });
因为等待的函数中有可能锁定和解锁mutex.
另外,condition variable也许有所谓的假醒,所以我们使用
[]{return !q.empty(); }来防止假醒对程序的影响。
注意,两个consumer的并发等待被通知次序是不确定的。
还要condition variable也提供给你一个接口允许你等待某个最大时间量:wait_for()用来等待一个时间段,wait_until()用来等待直到某个时间点。

最新文章

  1. ajax处理的方式
  2. Java字符串中常见的10个问题
  3. 常用的MIME类型
  4. [转]svn常用命令
  5. Find和FirstOrDefault()有什么区别?
  6. windows 上执行python pywin32.exe
  7. random circle
  8. hadoop(三):hdfs 机架感知
  9. 用Robotium 去实现点击imageview
  10. ok6410驱动usb摄像头
  11. Redis Sentinel的Redis集群(主从&amp;Sharding)高可用方案
  12. 【CSS】less 学习小结
  13. Linux - 主机的细部权限规划:ACL 的使用
  14. SSL WSS HTTPS
  15. react 监听页面滚动
  16. web 本地存储 (localStorage、sessionStorage)
  17. Oracle 数据库 Only 导出空表的方法
  18. SpringMVC——SpringMVC 的入门案例
  19. Keil debugging techniques and alternative printf (SWO function)
  20. php 常用的标签比较

热门文章

  1. SPSS数据分析—多维偏好分析(MPA)
  2. ubuntu-kylin16.04搭建lamp环境。
  3. 总结oninput、onchange与onpropertychange事件的用法和区别,onchange
  4. Flask-admin使用经验技巧总结
  5. 转网页WB.ExecWB控件打印方法
  6. 周爱民:真正的架构师是没有title的(图灵访谈)
  7. php知识案列分享
  8. Javascript学习笔记2.2 Javascript与DOM选项卡(滑动门)案例详解
  9. Java—Servlet技术
  10. Linux vi