-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheven_odd_mutex_cond.cc
58 lines (46 loc) · 1.06 KB
/
even_odd_mutex_cond.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
48
49
50
51
52
53
54
55
56
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int MAX = 10;
int count = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *even(void *arg)
{
while(count < MAX) {
pthread_mutex_lock(&mutex);
while(count % 2 != 0) {
pthread_cond_wait(&cond, &mutex);
}
printf("%d ", count++);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
void *odd(void *arg)
{
while(count < MAX) {
pthread_mutex_lock(&mutex);
while(count % 2 != 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("%d ", count++);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
int main()
{
pthread_t th[2];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&th[0], 0, &even, NULL);
pthread_create(&th[1], 0, &odd, NULL);
pthread_join(th[0], 0);
pthread_join(th[1], 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}