-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.cpp
executable file
·73 lines (62 loc) · 1.47 KB
/
test.cpp
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
/*
* Copyright (C) 2016, Íõ³¬ [wabcwang] , <[email protected]>.
* All Rights Reserved.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
sem_t bin_sem;
void *thread_function1(void *arg)
{
int i=0;
printf("thread_function1--------------sem_wait\n");
sem_wait(&bin_sem);
for(;;)
{
sem_wait(&bin_sem);
printf(" sem_wait %d\n",i++);
}
}
void *thread_function2(void *arg)
{
int i=0;
printf("thread_function2--------------sem_post\n");
while (1)
{
printf("sem_post %d\n",i++);
sem_post(&bin_sem);
sleep(5);
}
}
int main(int argc, char *argv[])
{
int res;
pthread_t a_thread;
void *thread_result;
res = sem_init(&bin_sem, 0, 0);
if (res != 0)
{
perror("Semaphore initialization failed");
}
printf("sem_init\n");
res = pthread_create(&a_thread, NULL, thread_function1, NULL);
if (res != 0)
{
perror("Thread creation failure");
}
printf("thread_function1\n");
//sleep (5);
printf("sleep\n");
res = pthread_create(&a_thread, NULL, thread_function2, NULL);
if (res != 0)
{
perror("Thread creation failure");
}
while (1)
{
}
return 0;
}