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