-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint_numbers.c
93 lines (78 loc) · 1.64 KB
/
print_numbers.c
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
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
bool turn = true;
int counter = 0;
void* even_thread(void* arg)
{
do
{
pthread_mutex_lock(&mutex);
if (counter % 2 == 0)
{
pthread_cond_wait(&condition, &mutex);
}
fprintf(stdout, "%d\n", counter);
fflush(stdout);
counter++;
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
sleep(3);
} while (1);
}
void* odd_thread(void* arg)
{
do
{
pthread_mutex_lock(&mutex);
if (counter % 2 != 0)
{
pthread_cond_wait(&condition, &mutex);
}
fprintf(stdout, "%d\n", counter);
fflush(stdout);
counter++;
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
sleep(1);
} while (1);
}
int main(int argc, char** argv)
{
pthread_t odd_thr, even_thr;
int rc = 0;
rc = pthread_create(&odd_thr, NULL, odd_thread, NULL);
if (rc < 0)
{
fprintf(stderr, "Error creating an odd thread! %d\n", errno);
fflush(stderr);
exit(EXIT_FAILURE);
}
rc = pthread_create(&even_thr, NULL, even_thread, NULL);
if (rc < 0)
{
fprintf(stderr, "Error creating an even thread! %d\n", errno);
fflush(stderr);
exit(EXIT_FAILURE);
}
rc = pthread_join(odd_thr, NULL);
if (rc < 0)
{
fprintf(stderr, "Error in pthread_join with odd thread! %d\n", errno);
fflush(stderr);
exit(EXIT_FAILURE);
}
rc = pthread_join(even_thr, NULL);
if (rc < 0)
{
fprintf(stderr, "Error in pthread_join with even thread! %d\n", errno);
fflush(stderr);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}