#include<thread>
#include<condition_variable>
#include<mutex>
#include<queue>
#include<stdio.h> template <class T>
class ThreadSafeQueue{
public:
void Insert(T value);
void Popup(T &value);
bool Empty() const; private:
mutable std::mutex mut_;
std::queue<T> que_;
std::condition_variable cond_;
}; template <class T>
void ThreadSafeQueue<T>::Insert(T value){
std::lock_guard<std::mutex> lk(mut_);
que_.push(value);
cond_.notify_one();
} template <class T>
void ThreadSafeQueue<T>::Popup(T &value){
std::unique_lock<std::mutex> lk(mut_);
cond_.wait(lk, [this]{return !que_.empty();}); // 如果lamda表达式 [this]{return !que_.empty(); 返回 true, 也就是队列非空,则上锁,继续执行下面的语句;
value = que_.front(); // 如果lamda表达式返回False, 也就是队列为空,则解开锁,该线程进入wait,阻塞模式,等待被唤醒
que_.pop();
} template <class T>
bool ThreadSafeQueue<T>::Empty() const{
std::lock_guard<std::mutex> lk(mut_);
return que_.empty();
} int main(){
ThreadSafeQueue<int> q;
int value=1;
std::thread t2(&ThreadSafeQueue<int>::Popup, &q, std::ref(value)); // 传引用参数的时候需要使用引用包装器std::ref
std::thread t1(&ThreadSafeQueue<int>::Insert, &q, 10);
printf("%d\n", value);
while(!q.Empty());
t1.join();
t2.join();
printf("%d\n", value);
return 0;
}

最新文章

  1. 【转】推荐10款最热门jQuery UI框架
  2. T-Sql(三)存储过程(Procedure)
  3. Find命令的用法
  4. NGUI UI Grid, two column
  5. Java EE注册三部曲(一步曲)
  6. php include
  7. vmware通过vmnet8共享本地网络
  8. 最小化安装Centos7后的部署(个人)
  9. asp.net(C#) 中 怎么使用 MongoDb
  10. 有几数组表单,js怎么获得数组并动态相加输出到文本框
  11. ecstore后台规格超过一定数量保存丢失
  12. 关于tomcat startup.bat启动后一闪而过的问题(转)
  13. Cookie和Session (转)
  14. 几乎没用到过的css 样式
  15. iOS动画特效
  16. Oracle 12cR1 RAC 在VMware Workstation上安装(上)—OS环境配置
  17. tomcat catalina.sh JAVA_OPTS参数说明与配置
  18. Github 开源:使用升讯威 Mapper( Sheng.Mapper)与 AutoMapper 互补,大幅提高开发效率!
  19. PHP 相对完整的分页
  20. App隐私条款

热门文章

  1. andriod升级保错问题归类
  2. JBOSS环境与应用部署
  3. sdio 移植st官方例程 stm32f103
  4. zerotier的planet服务器(根服务器)-搭建教程
  5. Windows下使用Fortran读取HDF5文件
  6. ubuntu 替换国内源,清华源
  7. java资源精华
  8. Python学习:Mysql(三)索引
  9. RTT笔记-分析自动初始化机制转
  10. oracle查看归档信息