Comment by gpderetta
5 hours ago
In C++ (with a bit of help from boost).
bool transfer(boost::synchronized<Account>& sync_from,
boost::synchronized<Account>& sync_to, int amount) {
auto [from, to] = synchronize(sync_from, sync_to);
if (from->withdraw(amount)) {
to->deposit(amount)
return true;
} else {
return false
}
}
Hopefully synchronized will make it into the standard library at some point, in the meantime it is not terribly hard to write it yourself if you do not want a boost dependency.
Does this avoid the dining philosopher deadlock?
yes, 'synchronize' uses a try_lock/backoff algorithm, same as std::scoped_lock.
edit: it could theoretically livelock, but I believe most if not all STM implementations also do not guarantee forward progress.