forked from nonstriater/Learn-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.c
71 lines (43 loc) · 1.07 KB
/
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
#include "stdio.h"
#include "pthread.h"
pthread_mutex_t mutex;
pthread_cond_t condition;
unsigned int i = 0;
void *threadFunc1(void *arg){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condition,&mutex);
pthread_mutex_unlock(&mutex);
printf("aaaaaaa %d\n",i);
pthread_exit((void *)0);
}
void *threadFunc2(void *arg){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condition,&mutex); //??? 这里人存在问题
pthread_mutex_unlock(&mutex);
printf("vbbbbbbbbbb %d\n",i);
pthread_exit((void *)0);
}
int main(int argc, char const *argv[])
{
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&condition,NULL);
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,threadFunc1,(void *)0);
pthread_create(&thread2,NULL,threadFunc2,(void *)0);
while(1){
pthread_mutex_lock(&mutex);
i++;
pthread_mutex_unlock(&mutex);
if (i==100000000)
{
//
pthread_cond_broadcast(&condition);
break;
}
}
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
pthread_cond_destroy(&condition);
pthread_mutex_destroy(&mutex);
return 0;
}