Comment by gpderetta
3 months 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.
Purely optimistic STM implementations that abort transactions early and don't permit other transactions to read uncommitted data can guarantee forward progress, and I believe that both Haskell's STM and Fraser and Harris's STM do, though I could easily be mistaken about that.
6 replies →