stdthread(9) deadlock deadlock

1. Scenario

May occur when two or more mutexes are required for a given operation.

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. The solution std::lock is locked at the same time

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;
}

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/123886817