-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrace.cpp
More file actions
132 lines (77 loc) · 2.15 KB
/
race.cpp
File metadata and controls
132 lines (77 loc) · 2.15 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/* Angshuman Ghosh 2017CS01
Program for atomic incrementing and decrementing of race variable and stooping the program when race becomes 100
*/
#include <iostream>
#include <cstdlib>
#include <list>
#include <pthread.h>
#include <unistd.h>
using namespace std;
int race = 0;
bool flag = false;
pthread_t thread[3];
pthread_mutex_t lock; // lock variable
pthread_cond_t done; // condition variable
void * inc(void * v){
int ret = 0;
while(flag != true){
sleep(1);
pthread_mutex_lock(&lock); // acquire lock
race += 3;
cout << "Increment thread : race = " << race << endl;
if(race == 100){
flag = true;
pthread_cond_signal(&done); // signal the waiter thread
pthread_mutex_unlock(&lock); // release lock
pthread_exit(&ret); // exit
}
else if(race >= 100){
pthread_mutex_unlock(&lock); // release lock
pthread_exit(&ret);
}
pthread_mutex_unlock(&lock); // release lock
}
pthread_exit(&ret);
}
void * dec(void * v){
int ret = 0;
while(flag != true){
sleep(1);
pthread_mutex_lock(&lock); // acquire lock
if(flag != true)
race -= 1;
cout << "Decrement thread : race = " << race << endl;
if(race == 100){
flag = true;
pthread_cond_signal(&done);
pthread_mutex_unlock(&lock); // release lock
pthread_exit(&ret);
}
pthread_mutex_unlock(&lock); // release lock
}
pthread_exit(&ret);
}
void * waiter(void * v){
int ret = 0;
pthread_mutex_lock(&lock); // acquire lock
while(race < 100){ // kept for spurious wakeup calls
pthread_cond_wait(&done, &lock); // wait on condition varible(release lock) for race to become 100
}
cout << "Waiting thread : Race is finally = " << race << endl;
pthread_mutex_unlock(&lock); // release lock
pthread_exit(&ret);
}
int main(){
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&done, NULL);
// create threads
pthread_create(&thread[2], NULL, waiter, NULL);
pthread_create(&thread[0], NULL, inc, NULL);
pthread_create(&thread[1], NULL, dec, NULL);
// join threads
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
pthread_join(thread[2], NULL);
pthread_cond_destroy(&done);
pthread_mutex_destroy(&lock);
}