-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23-semaphores-lock.c
55 lines (41 loc) · 980 Bytes
/
23-semaphores-lock.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
// Run Using "gcc -pthread 23_semaphores_lock.c && ./a.out"
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM 25
#define OPR 10000
sem_t sem;
typedef struct str {
sem_t* sem;
int* num;
} str;
void* locked_increment(void* vargp) {
str* s = (str*)vargp;
sem_t* sem = s->sem;
int* num = s->num;
for (int i = 0; i < OPR; i++) {
sem_wait(sem);
*num = *num + 1;
sem_post(sem);
}
return NULL;
}
int main() {
int num = 0;
pthread_t tid[NUM];
sem_init(&sem, 0, 1);
str s;
s.sem = &sem;
s.num = #
for (int i = 0; i < NUM; i++) {
pthread_create(&tid[i], NULL, locked_increment, (void*)&s);
}
for (int i = 0; i < NUM; i++) {
pthread_join(tid[i], NULL);
}
printf("Number = %d\n", num);
printf("Result: %s (Diff: %d)\n", num == NUM * OPR ? "PASS" : "FAIL", NUM * OPR - num);
return 0;
}