asfsa
#include <iostream> #include <mutex> #include <thread> class Account { private: double balance; std::mutex accountMutex; public: Account(double initialBalance) : balance(initialBalance) {} double getBalance() { return balance; } void deposit(double amount) { balance += amount; } bool withdraw(double amount) { if (balance >= amount) { balance -= amount; return true; } return false; } void lock() { accountMutex.lock(); } void unlock() { accountMutex.unlock(); } }; class Bank { private: Account& accountA; Account& accountB; public: Bank(Account& a, Account& b) : accountA(a), accountB(b) {} void transferAtoB(double amount) { accountA.lock(); if (accountA.withdraw(amount)) { accountB.deposit(amount); std::cout << "Transferred " << amount << " from Account A to Account B.\n"; } else { std::cout << "Not enough balance in Account A.\n"; } accountA.unlock(); } void transferBtoA(double amount) { accountB.lock(); if (accountB.withdraw(amount)) { accountA.deposit(amount); std::cout << "Transferred " << amount << " from Account B to Account A.\n"; } else { std::cout << "Not enough balance in Account B.\n"; } accountB.unlock(); } }; void transferAtoBThread(Bank& bank, double amount) { bank.transferAtoB(amount); } void transferBtoAThread(Bank& bank, double amount) { bank.transferBtoA(amount); } int main() { Account accountA(1000); Account accountB(500); Bank bank(accountA, accountB); std::thread t1(transferAtoBThread, std::ref(bank), 200); // Thread 1: A -> B std::thread t2(transferBtoAThread, std::ref(bank), 100); // Thread 2: B -> A t1.join(); t2.join(); std::cout << "Final Balance of Account A: " << accountA.getBalance() << "\n"; std::cout << "Final Balance of Account B: " << accountB.getBalance() << "\n"; return 0; }
Leave a Comment