首页 > 代码库 > C++11多线程04
C++11多线程04
死锁
#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; }
C++11多线程04
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。