标签:blog img print 方法 out ado main iostream 使用
死锁
#include <iostream> #include <thread> #include <mutex> #include <fstream> class LofFile { public: void shared_print(std::string name , int num) { std::lock_guard<std::mutex> locker(m_mutex) ; std::lock_guard<std::mutex> locker2(m_mutex2) ; std::cout<<name<<": "<<num<<std::endl; } void shared_print2(std::string name , int num) { std::lock_guard<std::mutex> locker2(m_mutex2) ; std::lock_guard<std::mutex> locker(m_mutex) ; std::cout<<name<<": "<<num<<std::endl; } private: std::mutex m_mutex ; std::mutex m_mutex2 ; }; void thread_fun(LofFile& log) { for(int i = 0 ; i>-100 ;i--) { log.shared_print("子线程",i); } } int main() { LofFile log ; std::thread t(thread_fun,std::ref(log)); for(int i=0 ;i<100;i++) { log.shared_print2("主线程",i); } t.join(); return 0; }
解决死锁方法1:使mutex顺序相同
#include <iostream> #include <thread> #include <mutex> #include <fstream> class LofFile { public: void shared_print(std::string name , int num) { std::lock_guard<std::mutex> locker(m_mutex) ; std::lock_guard<std::mutex> locker2(m_mutex2) ; std::cout<<name<<": "<<num<<std::endl; } void shared_print2(std::string name , int num) { std::lock_guard<std::mutex> locker(m_mutex) ; std::lock_guard<std::mutex> locker2(m_mutex2) ; std::cout<<name<<": "<<num<<std::endl; } private: std::mutex m_mutex ; std::mutex m_mutex2 ; }; void thread_fun(LofFile& log) { for(int i = 0 ; i>-100 ;i--) { log.shared_print("子线程",i); } } int main() { LofFile log ; std::thread t(thread_fun,std::ref(log)); for(int i=0 ;i<100;i++) { log.shared_print2("主线程",i); } t.join(); return 0; }
解决死锁方法2:使用std::lock
#include <iostream> #include <thread> #include <mutex> #include <fstream> class LofFile { public: void shared_print(std::string name , int num) { std::lock(m_mutex,m_mutex2); std::lock_guard<std::mutex> locker(m_mutex,std::adopt_lock) ; std::lock_guard<std::mutex> locker2(m_mutex2,std::adopt_lock) ; std::cout<<name<<": "<<num<<std::endl; } void shared_print2(std::string name , int num) { std::lock(m_mutex,m_mutex2); std::lock_guard<std::mutex> locker2(m_mutex2,std::adopt_lock) ; std::lock_guard<std::mutex> locker(m_mutex,std::adopt_lock) ; std::cout<<name<<": "<<num<<std::endl; } private: std::mutex m_mutex ; std::mutex m_mutex2 ; }; void thread_fun(LofFile& log) { for(int i = 0 ; i>-100 ;i--) { log.shared_print("子线程",i); } } int main() { LofFile log ; std::thread t(thread_fun,std::ref(log)); for(int i=0 ;i<100;i++) { log.shared_print2("主线程",i); } t.join(); return 0; }
标签:blog img print 方法 out ado main iostream 使用
原文地址:http://www.cnblogs.com/guozhikai/p/6105892.html