Untitled
unknown
c_cpp
9 months ago
2.4 kB
6
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) {
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);
cout << "Transferred " <<amount<< " from Account A to Account B"<<endl;
} else {
cout << "Not enough balance in Account A"<<endl;
}
accountA.unlock();
}
void transferAtoBThread(Bank& bank, double amount) {
bank.transferAtoB(amount);
}
void transferBtoAThread(Bank& bank, double amount) {
bank.transferBtoA(amount);
}
int main(){
int main() {
double user_accountA() , user_accountB();
cout<<"Enter user amount of account A:";
cin>>user_amount<<endl;
cout<<"Enter user amount of account B:";
cin>>user_amount<<endl;
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;
}
}
int main() {
Account accountA(1000);
Account accountB(500);
Bank bank(accountA, accountB);
thread t1(transferAtoBThread, std::ref(bank), 200); // Thread 1: A -> B
thread t2(transferBtoAThread, std::ref(bank), 100); // Thread 2: B -> A
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