stdthread(9)死锁deadlock
生活随笔
收集整理的這篇文章主要介紹了
stdthread(9)死锁deadlock
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 場景
一個給定操作需要兩個或兩個以上的互斥量時可能會出現(xiàn)。
class LogFile{ public:LogFile() {f.open("log.txt");}void shared_print(string msg,int idx) { lock_guard<mutex> locker1(m1);lock_guard<mutex> locker2(m2);f << msg << ":" << idx << endl;}void shared_print2(string msg, int idx) {lock_guard<mutex> locker2(m2);lock_guard<mutex> locker1(m1);f << msg << ":" << idx << endl;}protected: private:mutex m1;mutex m2;ofstream f;};void func(LogFile& log) {for (int i = 0; i > -100; i--) {log.shared_print2(string("sub thread:"), i);cout << "sub thread:" << i << endl;}} } using namespace multithread_02; int main() {LogFile log;thread t1(func,ref(log));for (int i = 0; i < 100; i++) {log.shared_print(string("main thread:"),i);cout << "main thread:" << i << endl;}if (t1.joinable()) t1.join();return 0; }2. 解決方法std::lock同時上鎖
void shared_print(string msg,int idx) { lock(m1,m2);lock_guard<mutex> locker1(m1,adopt_lock);lock_guard<mutex> locker2(m2,adopt_lock);f << msg << ":" << idx << endl; }void shared_print2(string msg, int idx) {lock(m1, m2);lock_guard<mutex> locker2(m2, adopt_lock);lock_guard<mutex> locker1(m1, adopt_lock);f << msg << ":" << idx << endl; }總結
以上是生活随笔為你收集整理的stdthread(9)死锁deadlock的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: stdthread(8)并发recurs
- 下一篇: LevelDB (1)概述