Untitled

safaa
 avatar
unknown
plain_text
19 days ago
2.7 kB
4
Indexable
#include <iostream>
#include <mutex>
#include <thread>

class Account {
private:
    double balance;
    std::mutex accountMutex;  // Mutex to ensure mutual exclusion during transactions

public:
    // Constructor to initialize balance
    Account(double initial_balance) : balance(initial_balance) {}

    // Method to get the balance
    double getBalance() {
        std::lock_guard<std::mutex> lock(accountMutex); // Lock the mutex to ensure thread-safe access
        return balance;
    }

    // Method to deposit money into the account
    void deposit(double amount) {
        std::lock_guard<std::mutex> lock(accountMutex); // Lock the mutex to ensure thread-safe access
        balance += amount;
    }

    // Method to withdraw money from the account
    bool withdraw(double amount) {
        std::lock_guard<std::mutex> lock(accountMutex); // Lock the mutex to ensure thread-safe access
        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) {}

    // Method to transfer money from accountA to accountB
    void transferFromAToB(double amount) {
        std::lock(accountA.accountMutex, accountB.accountMutex);  // Lock both account mutexes
        std::lock_guard<std::mutex> lockA(accountA.accountMutex, std::adopt_lock);
        std::lock_guard<std::mutex> lockB(accountB.accountMutex, std::adopt_lock);

        if (accountA.withdraw(amount)) {
            accountB.deposit(amount);
            std::cout << "Transferred " << amount << " from Account A to Account B\n";
        } else {
            std::cout << "Insufficient funds in Account A\n";
        }
    }

    // Method to transfer money from accountB to accountA
    void transferFromBToA(double amount) {
        std::lock(accountA.accountMutex, accountB.accountMutex);  // Lock both account mutexes
        std::lock_guard<std::mutex> lockA(accountA.accountMutex, std::adopt_lock);
        std::lock_guard<std::mutex> lockB(accountB.accountMutex, std::adopt_lock);

        if (accountB.withdraw(amount)) {
            accountA.deposit(amount);
            std::cout << "Transferred " << amount << " from Account B to Account A\n";
        } else {
            std::cout << "Insufficient funds in Account B\n";
        }
    }
};

int main() {
    Account accountA(1000);  // Account A starts with 1000
    Account accountB(500);   // Account B starts with 500

    Bank bank(accountA, accountB);

    // Create two threads to simulate transactions
    std::thread t1([&](){
        bank.transferFromAToB(200);  // Thread 1 transfers
Leave a Comment