-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPetersonAlgo.c
60 lines (51 loc) · 1.14 KB
/
PetersonAlgo.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
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <pthread.h>
int flag[2];
int turn,count=0,mode=0;
const int MAX = 1e9;
void lock_init()
{
flag[0] = flag[1] = 0;
turn = 0;
}
void lock(int curr)
{
flag[curr] = 1;
turn = 1-curr;
while (flag[1-curr]==1 && turn==1-curr) ;
}
void unlock(int curr)
{
flag[curr] = 0;
}
void* process(void *s)
{
int i = 0;
int curr = (int *)s;
printf("Process : %d\n", curr);
if(mode == 1)
lock(curr);
for (i=0; i<MAX; i++)
count++;
if(mode == 1)
unlock(curr);
}
void main()
{
pthread_t p1,p2,p3,p4;
printf("\nFirst without Lock\n");
pthread_create(&p1, NULL, process, (void*)0);
pthread_create(&p2, NULL, process, (void*)1);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Actual Count: %d and Expected Count: %d\n",count, MAX*2);
printf("\n\nNow with Lock\n");
count = 0;
mode = 1;
lock_init();
pthread_create(&p3, NULL, process, (void*)0);
pthread_create(&p4, NULL, process, (void*)1);
pthread_join(p3, NULL);
pthread_join(p4, NULL);
printf("Actual Count: %d and Expected Count: %d\n",count, MAX*2);
}