fork download
  1. // Online C compiler to run C program online
  2. #include <stdio.h>
  3. #include<pthread.h>
  4. #include<stdlib.h>
  5.  
  6. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  7. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  8.  
  9. const int MAX = 99;
  10. int count = 0;
  11.  
  12. void* even (void *ptr)
  13. {
  14. pthread_mutex_lock(&mutex);
  15. while(count <= MAX)
  16. {
  17. if(count%2 != 0)
  18. {
  19. pthread_cond_wait(&cond, &mutex);
  20. }
  21. printf("%d\n", count++);
  22. pthread_mutex_unlock(&mutex);
  23. pthread_cond_signal(&cond);
  24. }
  25. pthread_exit(0);
  26. }
  27.  
  28. void* odd (void *ptr)
  29. {
  30. pthread_mutex_lock(&mutex);
  31. while(count <= MAX)
  32. {
  33. if(count%2 == 0)
  34. {
  35. pthread_cond_wait(&cond, &mutex);
  36. }
  37. printf("%d\n", count++);
  38. pthread_mutex_unlock(&mutex);
  39. pthread_cond_signal(&cond);
  40. }
  41. pthread_exit(0);
  42. }
  43. int main()
  44. {
  45. pthread_t t1,t2;
  46. pthread_create(&t1, NULL, even, NULL);
  47. pthread_create(&t2, NULL, odd, NULL);
  48.  
  49. pthread_join(t1, 0);
  50. pthread_join(t2, 0);
  51. }
  52.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
0
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