I know I should use std::scoped_lock
to lock two mutexes at the same time. But I don't why.
I've read this post std::lock_guard or std::scoped_lock?. But I don't find anyone explains why there would a deadlock in the std::lock_guard
version.
#include <mutex>
#include <thread>
std::mutex mtx1;
std::mutex mtx2;
auto main(int argc, char* argv[]) -> int {
std::mutex mtx1;
std::mutex mtx2;
const auto thread_func = [&] {
std::scoped_lock lock(mtx1, mtx2);
// Why I can't lock like this
// std::lock_guard<std::mutex> lock1(mtx1);
// std::lock_guard<std::mutex> lock2(mtx2);
};
std::thread th1(thread_func);
std::thread th2(thread_func);
th1.join();
th2.join();
return 0;
}
Can someone explain this to me? Thank you.