-
Notifications
You must be signed in to change notification settings - Fork 0
/
task3.c
47 lines (39 loc) · 1015 Bytes
/
task3.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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define THREAD_COUNT 1000
#define THREAD_ITERATION 10000
#ifdef COMPLILE_TASK3A
int x = 0;
#else
#include <stdatomic.h>
_Atomic int x = 0;
#endif
void *increment(void *arg) {
for (int i = 0; i < THREAD_ITERATION; ++i) {
x++;
}
return NULL;
}
int main(void) {
int ret[THREAD_COUNT];
pthread_t thread[THREAD_COUNT];
// create 1000 Threads
for (int i = 0; i < THREAD_COUNT; i++) {
ret[i] = pthread_create(&thread[i], NULL, increment, NULL);
if (ret[i] != 0) {
fprintf(stderr, "ERROR %d: Cant create thread\n", ret[i]);
return EXIT_FAILURE;
}
}
// Wait for finish
for (int i = 0; i < THREAD_COUNT; i++) {
ret[i] = pthread_join(thread[i], NULL);
if (ret[i] != 0) {
fprintf(stderr, "ERROR %d: Cant join thread\n", ret[i]);
return EXIT_FAILURE;
}
}
printf("Result: %d\n", x);
return EXIT_SUCCESS;
}