-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
58 lines (48 loc) · 1.05 KB
/
mutex.cpp
File metadata and controls
58 lines (48 loc) · 1.05 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
56
57
58
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREAD 100
void* thread_add(void* arg);
void* thread_subtraction(void* arg);
long long sum;
pthread_mutex_t mutex;
int main()
{
pthread_t t_id[NUM_THREAD];
int i;
pthread_mutex_init(&mutex, NULL);
for (i = 0; i < NUM_THREAD; i++) {
if (i % 2) {
pthread_create(&t_id[i], NULL, thread_add, NULL);
} else {
pthread_create(&t_id[i], NULL, thread_subtraction, NULL);
}
}
for (i = 0; i < NUM_THREAD; i++) {
pthread_join(t_id[i], NULL);
}
printf("sum is %d\n", sum);
pthread_mutex_destroy(&mutex);
return 0;
}
void* thread_add(void* arg)
{
int i = 0;
pthread_mutex_lock(&mutex);
for (; i < 999999; i++) {
sum += i;
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void* thread_subtraction(void* arg)
{
int i = 0;
pthread_mutex_lock(&mutex);
for (; i < 999999; i++) {
sum -= i;
}
pthread_mutex_unlock(&mutex);
return NULL;
}