#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <mutex>
using namespace std;
// Shared flags to indicate process readiness (simulating atomic behavior)
atomic<bool> flag0(false); // Atomic flag for process 0
atomic<bool> flag1(false); // Atomic flag for process 1
mutex mtx; // Mutex for safe access to shared variables
void process(int id) {
int other = 1 - id; // Determine the other process
for (int i = 0; i < 3; ++i) { // Each process executes 3 times
{
// Lock the mutex to ensure safe access to shared variables
lock_guard<mutex> lock(mtx);
if (id == 0) {
flag0 = true; // Set the flag for process 0
} else {
flag1 = true; // Set the flag for process 1
}
// Busy-wait while the other process is active
while ((id == 0 && flag1) || (id == 1 && flag0)) {
// Do nothing, just wait
}
// Critical section
cout << "Process " << id << " is in critical section" << endl;
this_thread::sleep_for(chrono::seconds(1)); // Simulating critical section delay
if (id == 0) {
flag0 = false; // Reset flag after critical section
} else {
flag1 = false; // Reset flag after critical section
}
}
// Remainder section
cout << "Process " << id << " is in remainder section" << endl;
this_thread::sleep_for(chrono::milliseconds(500)); // Simulating remainder section delay
}
}
int main() {
// Creating two threads (simulating two processes)
thread t1(process, 0);
thread t2(process, 1);
// Start both threads
t1.join(); // Wait for thread t1 to finish
t2.join(); // Wait for thread t2 to finish
return 0;
}