0

What the target output of activity explain the codes

#include <chrono> #include <iostream> #include <stdlib.h> #include <thread> using namespace std; bool flag [2]; int turn; void P0() { while (true) { flag [0] = true;//declaring the desire to enter CS turn = 1;//giving the chance to other process (P1) while (flag [1] && turn == 1) /* wait for other process to exit CS and do nothing */; //critical section simulation here // let this function work for something(nothing) for 5 seconds cout<<"Process 0 is in critical section for 3 seconds"<<endl; for (int i=1; i<=3; i++) { std::this_thread::sleep_for(std::chrono::seconds(1)); cout<<"Process 0 on CS [Timer]: "<<i<<endl; } flag [0] = false; cout<<"Process 0 is in remainder section \n\n"; } } //same structure as P0 void P1() { while (true) { flag [1] = true; turn = 0; while (flag [0] && turn == 0) ; //critical section simulation here // let this function work for something(nothing) for 5 seconds cout<<"Process 1 is in critical section for 5 seconds"<<endl; for (int j=1; j<=5; j++) { std::this_thread::sleep_for(std::chrono::seconds(1)); cout<<"Process 1 on CS [Timer]: "<<j<<endl; } flag [1] = false; cout<<"Process 1 is in remainder section \n\n"; } } int main() { flag [0] = false; flag [1] = false; //run two threads here // one for P0 and another for P1 std::thread thr1, thr2; //declaring threads thr1= std::thread(P0); //P0 will be thr1 thr2= std::thread(P1); //P1 will be thr2 //thr1 and thr2 will join in the main function thr1.join(); thr2.join(); return 0; }

24th Jan 2021, 2:46 AM
Realyn Estellore
Realyn Estellore - avatar
1 ответ
+ 1
that allows two or more processes to share a single-use resource without conflict, using only shared memory for communication. https://en.m.wikipedia.org/wiki/Peterson%27s_algorithm
24th Jan 2021, 9:16 AM
JaScript
JaScript - avatar