Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab8/race.c
221 views
1
#include <pthread.h>
2
#include <stdio.h>
3
#define INC_LIMIT 50000
4
#define THREADS_NO 100
5
6
int a = 0, b = 0;
7
void* single_increment(void* arg)
8
{
9
int i;
10
for(i = 0; i < INC_LIMIT; i++)
11
a++;
12
return NULL;
13
}
14
15
void* double_increment(void* arg)
16
{
17
int i;
18
for(i = 0; i < INC_LIMIT; i++) {
19
b++;
20
b++;
21
}
22
return NULL;
23
}
24
25
int main()
26
{
27
int i;
28
pthread_t sinc_threads[THREADS_NO];
29
pthread_t dinc_threads[THREADS_NO];
30
31
for(i = 0; i < THREADS_NO; i++) {
32
pthread_create(&sinc_threads[i], NULL, single_increment, NULL);
33
pthread_create(&dinc_threads[i], NULL, double_increment, NULL);
34
}
35
36
for(i = 0; i < THREADS_NO; i++) {
37
pthread_join(sinc_threads[i], NULL);
38
pthread_join(dinc_threads[i], NULL);
39
}
40
41
printf("Single Incremented variable: got %d expected %d\n", a, INC_LIMIT*THREADS_NO);
42
printf("Double incremented variable: got %d expected %d\n", b, 2 * INC_LIMIT*THREADS_NO);
43
return 0;
44
}
45
46