stdthread死锁deadlock

Posted thefist11

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了stdthread死锁deadlock相关的知识,希望对你有一定的参考价值。

1. 场景

一个给定操作需要两个或两个以上的互斥量时可能会出现。

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死锁deadlock的主要内容,如果未能解决你的问题,请参考以下文章

利用pt-deadlock-logger监控死锁

OS——死锁

OS——死锁

OS——死锁

OS——死锁

stdthread并发recursive_mutex 递归锁