#include #include #include using namespace std ; class BankAccount { public: BankAccount(int initialBalance) : balance_(initialBalance) {} void deposit(int amount) { recursiveMutexObject.lock() ; balance_ += amount; cout << "Deposited " << amount << ". New balance: " << balance_ << endl; recursiveMutexObject.unlock() ; } void withdraw(int amount) { recursiveMutexObject.lock() ; // Lock this account if (balance_ >= amount) { balance_ -= amount; cout << "Withdrew " << amount << ". New balance: " << balance_ << endl; } else { cout << "Insufficient funds to withdraw " << amount << ". Current balance: " << balance_ << endl; } recursiveMutexObject.unlock() ; // Lock this account } // This method demonstrates recursive locking void transfer(BankAccount& otherAccount, int amount) { recursiveMutexObject.lock() ; // Lock this account cout << "Initiating transfer of " << amount << " from this account." << endl; withdraw(amount); // This will re-acquire the lock on 'this' account otherAccount.deposit(amount); // This will attempt to acquire the lock on 'otherAccount' cout << "Transfer complete." << endl; recursiveMutexObject.unlock() ; } int getBalance() { return balance_; } private: recursive_mutex recursiveMutexObject ; int balance_; }; int main() { BankAccount account1(1000); BankAccount account2(500); // Demonstrate recursive locking within a single thread account1.transfer(account2, 200); cout << "Final balance of account1: " << account1.getBalance() << endl; cout << "Final balance of account2: " << account2.getBalance() << endl; return 0; }