//OPT: -lpthread #include #include #include #include #include using namespace std; using namespace std::chrono; class bankaccount { public: bankaccount() { bal = 0; } void deposit(int amt) { m.lock(); int currbal = bal; this_thread::sleep_for(milliseconds(1)); bal = currbal + amt; m.unlock(); } void withdraw(int amt) { m.lock(); int currbal = bal; this_thread::sleep_for(milliseconds(1)); bal = currbal - amt; m.unlock(); } int balance() { return bal; } private: mutex m; int bal; // in cents }; void earner(bankaccount &a) { a.deposit(1000); // add ten dollars a.deposit(1000); // add ten dollars a.deposit(1000); // add ten dollars } void spender(bankaccount &a) { a.withdraw(800); // spend eight dollars a.withdraw(800); // spend eight dollars a.withdraw(800); // spend eight dollars } int main(int argc, char **argv) { bankaccount acct; thread t1(earner,ref(acct)); thread t2(spender,ref(acct)); t1.join(); t2.join(); cout << "balance = " << acct.balance() << endl; }