-
Notifications
You must be signed in to change notification settings - Fork 367
Expand file tree
/
Copy pathpeterson_algo.c
More file actions
72 lines (55 loc) · 1.49 KB
/
peterson_algo.c
File metadata and controls
72 lines (55 loc) · 1.49 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
// Shared variables
bool flag[2];
int turn;
// Process 0
void* process0(void* arg)
{
while (true) {
flag[0] = true;
turn = 1;
// Wait until Process 1 is not in its critical section or it's not its turn
while (flag[1] && turn == 1) {}
// Critical section
printf("Process 0 is in its critical section.\n");
// Exit critical section
flag[0] = false;
// Remainder section
printf("Process 0 is in its remainder section.\n");
}
return NULL;
}
// Process 1
void* process1(void* arg)
{
while (true) {
flag[1] = true;
turn = 0;
// Wait until Process 0 is not in its critical section or it's not its turn
while (flag[0] && turn == 0) {}
// Critical section
printf("Process 1 is in its critical section.\n");
// Exit critical section
flag[1] = false;
// Remainder section
printf("Process 1 is in its remainder section.\n");
}
return NULL;
}
int main()
{
// Initialize shared variables
flag[0] = false;
flag[1] = false;
turn = 0;
// Create two threads for the two processes
pthread_t thread0, thread1;
pthread_create(&thread0, NULL, process0, NULL);
pthread_create(&thread1, NULL, process1, NULL);
// Wait for the threads to finish (which will be never)
pthread_join(thread0, NULL);
pthread_join(thread1, NULL);
return 0;
}