互斥对象的使用方法
来源:互联网 发布:雅米网络兼职怎么做 编辑:程序博客网 时间:2024/06/08 12:13
#include<iostream>#include<string>#include<thread>#include<mutex>using namespace std;mutex mu;void shared_print(string msg, int id){ mu.lock(); cout <<msg << id << endl; mu.unlock();}void function_1(){ for (int i = 0; i > -10; i--) { shared_print("From t1:", i); //cout << "From t1:" << i << endl;//其实竞争的是cout }}int main(){ thread t1(function_1); for (int i = 0; i < 10; i++) { shared_print("From main:", i); //cout << "From main:" << i << endl; } t1.join(); return 0;}
更好的方法
#include<iostream>#include<string>#include<thread>#include<mutex>#include<fstream>using namespace std;//mutex mu;//void shared_print(string msg, int id)//{// lock_guard<mutex> guard(mu);// //mu.lock();// cout <<msg << id << endl;//若出现异常,则cout会被永远的锁住// //mu.unlock();//}class LofFile{public: LofFile() { f.open("log.txt"); } void shared_print(string id, int value) { lock_guard<mutex> locker(m_mutex); f << "From" << id << ":" << value << endl; }protected:private: mutex m_mutex; ofstream f;};void function_1(LofFile& log){ for (int i = 0; i > -10; i--) { log.shared_print("From t1:", i); //cout << "From t1:" << i << endl;//其实竞争的是cout }}int main(){ LofFile log; thread t1(function_1,ref(log)); for (int i = 0; i < 10; i++) { log.shared_print("From main:", i); //cout << "From main:" << i << endl; } t1.join(); return 0;}
阅读全文
0 0
- 互斥对象的使用方法
- 多线程的互斥对象
- 互斥对象的概念
- C++的对象互斥访问
- 互斥变量内核对象的遗留问题
- 基于互斥对象的线程同步
- 基于互斥对象的线程同步
- c++ 对象的互斥访问
- 创建互斥对象
- 对象互斥
- 互斥对象(转)
- 互斥对象
- 互斥内核对象
- 互斥内核对象
- 互斥对象
- 互斥对象 Mutex
- 互斥对象
- 互斥对象
- HIbernate映射
- CV牛人主页
- 基于物理着色(PBS)及Unity中的实现
- Appium测试混合应用失败后截图注意事项
- 菜鸟成长之路
- 互斥对象的使用方法
- CentOS 安装rz和sz命令
- Linux 使用 Gitolite 架設 Git Server
- h5新特性:<style scoped>
- 《Java-要建立面向接口编程的思想》---做个记录而已
- MyEclipse启动Tomcat错误org.apache.tomcat.jni.Error: 730060: ????l????????????ó???????????òl????÷?ú?
- android Gson解析json数据
- androidStudio升级到2.3之后打包安装不了
- 用二维数组的方式打印杨辉三角形