Medium
Symmetric try_lock and back-off between two threads
Both threads are written to avoid deadlock by backing off (releasing their first lock and yielding) whenever the second lock isn't immediately available. On a system where the two threads happen to run in near-lockstep, what can happen?
main.cpp
void threadA() {
while (true) {
mtx1.lock();
if (mtx2.try_lock()) {
/* do work */
mtx2.unlock();
mtx1.unlock();
break;
}
mtx1.unlock();
std::this_thread::yield();
}
}
void threadB() {
while (true) {
mtx2.lock();
if (mtx1.try_lock()) {
/* do work */
mtx1.unlock();
mtx2.unlock();
break;
}
mtx2.unlock();
std::this_thread::yield();
}
}7 of 51 in Concurrency