-
Notifications
You must be signed in to change notification settings - Fork 0
/
m_thread.c
74 lines (51 loc) · 1.21 KB
/
m_thread.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
/*************************************************************************
> File Name: m_thread.c
> Author:
> Mail:
> Created Time: 2017年10月19日 星期四 16时54分45秒
************************************************************************/
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include<stdlib.h>
void *consumer(void *arg);
int time_to_exit = 0;
int num;
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, consumer, NULL);
if(res != 0) {
perror("Thread creation failed");
exit(1);
}
while(1) {
if(time_to_exit ==0) {
num = rand()%1000;
printf("number + 1 = : %d\n",num+1);
time_to_exit = 1;
}
else {
sleep(1);
}
}
res = pthread_join(a_thread, &thread_result);
if( res != 0 ) {
perror("Thread join failed");
exit(1);
}
exit(0);
}
void * consumer(void * arg) {
while(1) {
if(time_to_exit != 0) {
printf("number - 1 = : %d\n",num-1);
time_to_exit = 0;
}
else {
sleep(1);
}
}
}