Medium
Two threads locking two mutexes in opposite order
Does this program reliably deadlock, reliably complete, or is the outcome scheduling-dependent?
main.cpp
#include <mutex>
#include <thread>
#include <chrono>
std::mutex A, B;
void thread1() {
std::lock_guard<std::mutex> lockA(A);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> lockB(B);
}
void thread2() {
std::lock_guard<std::mutex> lockB(B);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> lockA(A);
}
int main() {
std::thread t1(thread1), t2(thread2);
t1.join();
t2.join();
}7 of 53 in Operating Systems