Ordered By Address
This transfer function uses the standard trick of ordering two locks by their addresses so no pair of callers can build a cycle:
struct Account { std::mutex m; long cents; };
void transfer(Account& from, Account& to, long amount) {
if (&from.m < &to.m) {
from.m.lock();
to.m.lock();
} else {
to.m.lock();
from.m.lock();
}
from.cents -= amount;
to.cents += amount;
from.m.unlock();
to.m.unlock();
}
The ordering is right and two threads calling transfer(a, b, 100) and transfer(b, a, 250) never deadlock. One caller still hangs forever. Which one?
Sign in to answer questions and track your progress
Sign In