-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore.cpp
52 lines (45 loc) · 970 Bytes
/
semaphore.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
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
void* read(void* arg);
void* accu(void* arg);
//sem_one for accu sum
static sem_t sem_one;
//sem_two for read num
static sem_t sem_two;
static int num;
int main(int a, char* n[])
{
pthread_t tid1, tid2;
sem_init(&sem_one, 0, 0);
sem_init(&sem_two, 0, 1);
pthread_create(&tid1, NULL, read, NULL);
pthread_create(&tid2, NULL, accu, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&sem_one);
sem_destroy(&sem_two);
return 0;
}
void* read(void* arg)
{
int i;
for (i = 0; i < 5; i++) {
fputs("input:", stdout);
sem_wait(&sem_two);
scanf("%d", &num);
sem_post(&sem_one);
}
return NULL;
}
void* accu(void* arg)
{
int sum = 0, i;
for (i = 0; i < 5; i++) {
sem_wait(&sem_one);
sum += num;
sem_post(&sem_two);
}
printf("result:%d \n", sum);
return NULL;
}