回答編集履歴
1
追記
test
CHANGED
@@ -1,3 +1,60 @@
|
|
1
1
|
pthread_mutex 使って排他すればいい。
|
2
2
|
https://qiita.com/ryo_manba/items/e48faf2ba84f9e5d31c8
|
3
3
|
|
4
|
+
```C
|
5
|
+
#include <stdio.h>
|
6
|
+
#include <pthread.h>
|
7
|
+
|
8
|
+
const size_t loop_max = 10000;
|
9
|
+
|
10
|
+
int sum = 0;
|
11
|
+
pthread_mutex_t mtx;
|
12
|
+
|
13
|
+
void f1() {
|
14
|
+
size_t i;
|
15
|
+
printf("start thread1\n");
|
16
|
+
for(i=0; i<loop_max; i++){
|
17
|
+
pthread_mutex_lock(&mtx);
|
18
|
+
sum += 2;
|
19
|
+
pthread_mutex_unlock(&mtx);
|
20
|
+
}
|
21
|
+
printf("finish thread1\n");
|
22
|
+
}
|
23
|
+
|
24
|
+
void f2() {
|
25
|
+
size_t i;
|
26
|
+
printf("start thread2\n");
|
27
|
+
for(i=0; i<loop_max; i++){
|
28
|
+
pthread_mutex_lock(&mtx);
|
29
|
+
sum += 3;
|
30
|
+
pthread_mutex_unlock(&mtx);
|
31
|
+
}
|
32
|
+
printf("finish thread2\n");
|
33
|
+
}
|
34
|
+
|
35
|
+
int main() {
|
36
|
+
pthread_t thread1, thread2;
|
37
|
+
pthread_mutex_init(&mtx, NULL);
|
38
|
+
|
39
|
+
pthread_create(&thread1,NULL,(void *)f1,NULL);
|
40
|
+
pthread_create(&thread2,NULL,(void *)f2,NULL);
|
41
|
+
|
42
|
+
pthread_join(thread1,NULL);
|
43
|
+
pthread_join(thread2,NULL);
|
44
|
+
|
45
|
+
pthread_mutex_destroy(&mtx);
|
46
|
+
printf("done\n");
|
47
|
+
printf("sum=%d\n", sum);
|
48
|
+
return 0;
|
49
|
+
}
|
50
|
+
```
|
51
|
+
実行結果:
|
52
|
+
```
|
53
|
+
start thread1
|
54
|
+
start thread2
|
55
|
+
finish thread1
|
56
|
+
finish thread2
|
57
|
+
done
|
58
|
+
sum=50000
|
59
|
+
```
|
60
|
+
|