#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
using namespace std;
// Shared variables
atomic<bool> flag0(false); // Flag for process 0
atomic<bool> flag1(false); // Flag for process 1
atomic<int> turn(0); // Variable for turn-based coordination
void process(int id) {
int other = 1 - id; // Determine the other process
for (int i = 0; i < 3; ++i) { // Run the process three times
// Request to enter critical section
if (id == 0) {
flag0 = true; // Mark process 0 as requesting critical section
turn = 1; // Give turn to process 1
} else {
flag1 = true; // Mark process 1 as requesting critical section
turn = 0; // Give turn to process 0
}
// Wait until the other process exits critical section
while ((id == 0 && flag1 && turn == 1) || (id == 1 && flag0 && turn == 0)) {
// Busy wait (not ideal, but needed for mutual exclusion)
}
// Critical Section
cout << "Process " << id << " is in critical section" << endl;
this_thread::sleep_for(chrono::seconds(1)); // Simulate work in the critical section
// Exit critical section
if (id == 0) {
flag0 = false; // Reset flag for process 0
} else {
flag1 = false; // Reset flag for process 1
}
cout << "Process " << id << " is in remainder section" << endl;
this_thread::sleep_for(chrono::milliseconds(500)); // Simulate work in the remainder section
}
}
int main() {
// Create two threads representing two processes
thread t1(process, 0);
thread t2(process, 1);
// Start both threads (they start automatically upon creation)
// Wait for threads to complete
t1.join();
t2.join();
return 0;
}