-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconditional-variable.cc
49 lines (35 loc) · 1.05 KB
/
conditional-variable.cc
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
//condition variable is used to execute thread as per some condition like below is example for add and withdrow money
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex m;
int currentBalance = 0;
void addMoney(int amount) {
lock_guard<mutex> lg(m);
cout << "thread addMoney" << endl;
currentBalance = currentBalance + amount;
cout << "Amount Added Current Balance is " << currentBalance << endl;
cv.notify_one();
}
void withdrowMoney(int amount) {
unique_lock<mutex> ul(m);
cout << "thread withdrowMoney" << endl;
cv.wait(ul, []{return (currentBalance != 0) ? true : false ; });
if(currentBalance >= amount) {
currentBalance = currentBalance - amount;
cout << "Amount Deducted " << amount << endl;
} else {
cout << "Amount cannot be deducted because of insufficient balance" << endl;
}
cout << "current balance is " << currentBalance << endl;
}
int main() {
thread t1(addMoney, 500);
thread t2(withdrowMoney, 600);
t1.join();
t2.join();
return 0;
}