Untitled
unknown
c_cpp
22 days ago
2.2 kB
4
Indexable
#include <iostream> #include <mutex> #include <thread> using namespace std; class Account { private: double balance; mutex accountMutex; public: Account(double initialBalance) : balance(initialBalance) {} double getBalance() { return balance; } void deposit(double amount) { lock_guard<mutex> lock(accountMutex); balance += amount; } bool withdraw(double amount) { lock_guard<mutex> lock(accountMutex); if (balance >= amount) { balance -= amount; return true; } return false; } }; class Bank { private: Account& accountA; Account& accountB; public: Bank(Account& a, Account& b) : accountA(a), accountB(b) {} void transferAtoB(double amount) { if (accountA.withdraw(amount)) { accountB.deposit(amount); cout << "Transferred " << amount << " from Account A to Account B" << endl; } else { cout << "Not enough balance in Account A" << endl; } } void transferBtoA(double amount) { if (accountB.withdraw(amount)) { accountA.deposit(amount); cout << "Transferred " << amount << " from Account B to Account A" << endl; } else { cout << "Not enough balance in Account B" << endl; } } }; void transferAtoBThread(Bank& bank, double amount) { bank.transferAtoB(amount); } void transferBtoAThread(Bank& bank, double amount) { bank.transferBtoA(amount); } int main() { double user_amountA, user_amountB; cout << "Enter user amount of account A: "; cin >> user_amountA; cout << "Enter user amount of account B: "; cin >> user_amountB; Account accountA(user_amountA); Account accountB(user_amountB); Bank bank(accountA, accountB); thread t1(transferAtoBThread, std::ref(bank), 200); thread t2(transferBtoAThread, std::ref(bank), 100); t1.join(); t2.join(); cout << "Final Balance of Account A: " << accountA.getBalance() << "\n"; cout << "Final Balance of Account B: " << accountB.getBalance() << "\n"; return 0; }
Editor is loading...
Leave a Comment