-
Notifications
You must be signed in to change notification settings - Fork 0
/
12-mutex-locks.c
63 lines (48 loc) · 1.2 KB
/
12-mutex-locks.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
// Run Using "gcc -pthread 12_mutex_locks.c && ./a.out"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void* simple_increment(void* vargp) {
int* num = (int*)vargp;
for (int i = 0; i < 10000; i++) {
*num = *num + 1;
}
return NULL;
}
pthread_mutex_t status;
typedef struct lock {
pthread_mutex_t* status;
int *num;
} lock;
void* locked_increment(void* vargp) {
lock* l = (lock*)vargp;
int* num = l -> num;
pthread_mutex_t* status = l -> status;
for (int i = 0; i < 10000; i++) {
pthread_mutex_lock(status);
*num = *num + 1;
pthread_mutex_unlock(status);
}
return NULL;
}
int main() {
int num;
pthread_t tid[5];
// Mutex Locked Increment
printf("Locked Increment:\n");
num = 0;
lock l;
pthread_mutex_init(&status, NULL);
l.status = &status;
l.num = #
for (int i=0; i<5; i++) {
pthread_create(&tid[i], NULL, locked_increment, (void*)&l);
}
for (int i=0; i<5; i++) {
pthread_join(tid[i], NULL);
}
printf("Number = %d\n", num);
printf("Result: %s (Diff: %d)\n", num == 50000 ? "PASS" : "FAIL", 50000 - num);
return 0;
}