fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4. #include <atomic>
  5. #include <mutex>
  6.  
  7. using namespace std;
  8.  
  9. // Shared flags to indicate process readiness (simulating atomic behavior)
  10. atomic<bool> flag0(false); // Atomic flag for process 0
  11. atomic<bool> flag1(false); // Atomic flag for process 1
  12. mutex mtx; // Mutex for safe access to shared variables
  13.  
  14. void process(int id) {
  15. int other = 1 - id; // Determine the other process
  16.  
  17. for (int i = 0; i < 3; ++i) { // Each process executes 3 times
  18. {
  19. // Lock the mutex to ensure safe access to shared variables
  20. lock_guard<mutex> lock(mtx);
  21. if (id == 0) {
  22. flag0 = true; // Set the flag for process 0
  23. } else {
  24. flag1 = true; // Set the flag for process 1
  25. }
  26.  
  27. // Busy-wait while the other process is active
  28. while ((id == 0 && flag1) || (id == 1 && flag0)) {
  29. // Do nothing, just wait
  30. }
  31.  
  32. // Critical section
  33. cout << "Process " << id << " is in critical section" << endl;
  34. this_thread::sleep_for(chrono::seconds(1)); // Simulating critical section delay
  35.  
  36. if (id == 0) {
  37. flag0 = false; // Reset flag after critical section
  38. } else {
  39. flag1 = false; // Reset flag after critical section
  40. }
  41. }
  42.  
  43. // Remainder section
  44. cout << "Process " << id << " is in remainder section" << endl;
  45. this_thread::sleep_for(chrono::milliseconds(500)); // Simulating remainder section delay
  46. }
  47. }
  48.  
  49. int main() {
  50. // Creating two threads (simulating two processes)
  51. thread t1(process, 0);
  52. thread t2(process, 1);
  53.  
  54. // Start both threads
  55. t1.join(); // Wait for thread t1 to finish
  56. t2.join(); // Wait for thread t2 to finish
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5260KB
stdin
Standard input is empty
stdout
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
Process 0 is in critical section
Process 0 is in remainder section