#include <iostream>
#include <thread>
#include <mutex>
class Account {
public:
Account(int balance) : balance_(balance) {}
void transfer(Account& to, int amount) {
std::unique_lock<std::mutex> lock_from(mutex_, std::defer_lock);
std::unique_lock<std::mutex> lock_to(to.mutex_, std::defer_lock);
std::lock(lock_from, lock_to);
if (balance_ >= amount) {
balance_ -= amount;
to.balance_ += amount;
std::cout << "Transfer successful\n";
} else {
std::cout << "Insufficient funds\n";
}
}
private:
int balance_;
std::mutex mutex_;
};
int main() {
Account acc1(1000);
Account acc2(500);
std::thread t1(&Account::transfer, &acc1, std::ref(acc2), 300);
std::thread t2(&Account::transfer, &acc2, std::ref(acc1), 200);
t1.join();
t2.join();
return 0;
}