-
Notifications
You must be signed in to change notification settings - Fork 0
/
pthread5.c
55 lines (48 loc) · 882 Bytes
/
pthread5.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
static sem_t my_sem;
int the_end;
void *thread_one(void *p)
{
while (!the_end)
{
printf("Je t'attend !\n");
sem_wait(&my_sem);
}
printf("OK, je sors !\n");
pthread_exit(0);
}
void *thread_two(void *p)
{
register int i;
for (i = 0; i < 5; i++)
{
printf("J'arrive %d!", i);
sem_post(&my_sem);
sleep(1);
}
the_end = 1;
sem_post(&my_sem);
pthread_exit(0);
}
int main (int ac, char **av)
{
pthread_t threads[2];
void *ret;
sem_init(&my_sem, 0, 0);
if (pthread_create(&threads[0], NULL, thread_one, NULL) < 0)
{
printf("error create pthread 1\n");
exit(2);
}
if (pthread_create(&threads[1], NULL, thread_two, NULL) < 0)
{
printf("error create pthread 2\n");
exit(2);
}
pthread_join(threads[0], &ret);
pthread_join(threads[1], &ret);
}