fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4.  
  5. using namespace std;
  6.  
  7. volatile int turn = 0; // Global variable controlling process execution order
  8.  
  9. void process(int id) {
  10. int other = 1 - id;
  11.  
  12. for (int i = 0; i < 3; ++i) {
  13. // Busy wait until the process gets its turn
  14. while (turn != id) {
  15. // Do nothing, just wait
  16. }
  17.  
  18. // Critical section
  19. cout << "Process " << id << " is in critical section" << endl;
  20. this_thread::sleep_for(chrono::seconds(1)); // Simulating critical section delay
  21.  
  22. // Change turn to allow the other process to execute
  23. turn = other;
  24.  
  25. // Remainder section
  26. cout << "Process " << id << " is in remainder section" << endl;
  27. this_thread::sleep_for(chrono::milliseconds(500)); // Simulating remainder section delay
  28. }
  29. }
  30.  
  31. int main() {
  32. // Creating two threads (simulating two processes)
  33. thread t1(process, 0);
  34. thread t2(process, 1);
  35.  
  36. // Wait for both threads to finish
  37. t1.join();
  38. t2.join();
  39.  
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 2.99s 5288KB
stdin
Standard input is empty
stdout
Process 0 is in critical section
Process 0 is in remainder section
Process 1 is in critical section
Process 1 is in remainder section
Process 0 is in critical section
Process 0 is in remainder section
Process 1 is in critical section
Process 1 is in remainder section
Process 0 is in critical section
Process 0 is in remainder section
Process 1 is in critical section
Process 1 is in remainder section