-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpetersonsalgo.cpp
More file actions
50 lines (41 loc) · 1.3 KB
/
petersonsalgo.cpp
File metadata and controls
50 lines (41 loc) · 1.3 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
// Peterson’s Algorithm is a classic software-based solution for the critical section problem in operating systems. It ensures mutual exclusion between two processes
// It guarantees: 1. Mutual Exclusion 2. Progress 3. Bounded Waiting
// Can be extended to multiple processes using filter algorithm (don't study)
// Can also use Ticket lock but it uses fetch-and-add atomic instruction
#include <iostream>
#include <thread>
using namespace std;
bool flag[2];
int turn;
int counter;
void init() {
flag[0] = false;
flag[1] = false;
turn = 0;
}
void algo(int id){
int other = 1-id;
flag[id] = true;
turn = 1-id;
while(flag[other] && turn==other){
// can yeild cpu here to increase performance
// if cpu yeild is used then memory ordering instrtuction is also required to maintain correct order of instruction execution
}
//critical section
for(int i=0;i<1e7;i++) counter++;
cout<<"Process "<<id<<" is in critical section"<<endl;
flag[id] = false;
//remainder section
cout<<"Process "<<id<<" is in remainder section"<<endl;
return;
}
int main(){
cout<<"Peterson's Algorithm Initialized"<<endl;
init();
thread t1(algo,0);
thread t2(algo,1);
t1.join();
t2.join();
cout<<"Final Counter Value: "<<counter<<endl;
return 0;
}