#include #include #include #include struct Account { std::mutex mutex; int balance = 1000; }; void transfer_one(Account& from, Account& to) { if (&from == &to) return; std::scoped_lock lock(from.mutex, to.mutex); assert(from.balance > 0); --from.balance; ++to.balance; } int main() { Account a; Account b; std::thread worker([&] { for (int i = 0; i < 100; ++i) transfer_one(a, b); }); for (int i = 0; i < 100; ++i) transfer_one(b, a); worker.join(); assert(a.balance == 1000 && b.balance == 1000); transfer_one(a, a); assert(a.balance + b.balance == 2000); std::cout << a.balance << ' ' << b.balance << '\n'; }