1.シナリオ
特定の操作に2つ以上のミューテックスが必要な場合に発生する可能性があります。
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;
}