-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathPthreads_MutexLock_Example.c
More file actions
55 lines (41 loc) · 1.08 KB
/
Pthreads_MutexLock_Example.c
File metadata and controls
55 lines (41 loc) · 1.08 KB
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 <pthread.h>
// Compile with -pthread
// Create a mutex this ready to be locked!
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int sum = 0;
void *countgold(void *param) {
int i;
// Same thread that locks the mutex must unlock it
// Critical section is just 'sum += 1'
// However locking and unlocking a million times
// has significant overhead in this simple answer
pthread_mutex_lock(&m);
// Other threads that call lock will have to wait until we call unlock
for (i = 0; i < 10000000; i++) {
sum += 1;
}
pthread_mutex_unlock(&m);
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, countgold, NULL);
pthread_create(&tid2, NULL, countgold, NULL);
//Wait for both threads to finish:
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("ARRRRG sum is %d\n", sum);
return 0;
}
/*
With mutex vs. Without mutex
With:
ARRRRG sum is 20000000
Without:
ARRRRG sum is 12617372
ARRRRG sum is 17073678
ARRRRG sum is 14664576
...
(The value may differ)
*/