by ridiculous_fish · 2y ago · 0 comments
A classic example is a set of bank accounts, atomically transacting with each other. Fine-grained per-account locking is possible, but risks deadlock due to lock ordering inversion. A simple solution is to replace per-account locks with a singleton global lock, covering all accounts. Any transaction must first acquire this lock, and now deadlock is impossible.
But this is an awkward fit for Rust, whose locks want to own the data they protect. What's the best way to express a global lock, enforcing that certain data may only be accessed while the global lock is held?
One piece of advice I'd suggest is, write APIs which take that MyTransferToken to signify that you must take the lock before calling them, it can be a unit type (a Zero Size type, a struct with no members) at the start if you like, but I suspect you'll find that across several functions which take that MyTransferToken you realise actually the data I was going to put in a separate parameter is really always accompanying that token, and so it might as well go inside the the MyTransferToken and before you know it your unit type that was just to ensure correct locking is in fact an object with important data protected by the lock.
Mutex<HashMap<CustomerID, Account>>
Instead of HashMap<CustomerID, Mutex<Account>>
Using a singleton is kind of overkill.But in the real world you'd probably use a transactional database for this (there are a few in memory options) with retries.
[1]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html [2]: https://doc.rust-lang.org/std/sync/struct.OnceLock.html [3]: https://crates.io/crates/once_cell
When you lock, the returned MutexGuard is owned, so you can pass it around or return it and it’s only dropped when it ultimately goes out of scope.