-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09_conditional_variable.cpp
More file actions
54 lines (45 loc) · 1.23 KB
/
09_conditional_variable.cpp
File metadata and controls
54 lines (45 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
int balance = 0;
condition_variable cv;
mutex mut;
void withDrawMoney(int amount)
{
cout << "Inside Withdraw Money\n";
unique_lock<mutex> ul(mut);
// wait for other thread based on a condition
cout << "Waiting for the condition to get updated\n";
cout << "Wait releases the mutex and waits upon the condition\n";
cv.wait(ul, []
{ return (balance != 0) ? true : false; });
if (balance >= amount)
{
balance -= amount;
cout << "Amount deducted: " << amount << "\n";
}
else
{
cout << "Insufficient balance, current balance is less than " << amount << "\n";
}
cout << "Balance: " << balance << "\n";
}
void addMoney(int amount)
{
cout << "Inside Add Money\n";
lock_guard<mutex> lg(mut);
balance += amount;
cout << "Amount added " << amount << "\n";
cout << "Balance = " << balance << "\n";
// NOTE: Important to notify the other thread after the work has been done
cv.notify_one();
}
int main()
{
thread withDrawMoneyThread(withDrawMoney, 500);
thread addMoneyThread(addMoney, 500);
withDrawMoneyThread.join();
addMoneyThread.join();
return 0;
}