fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4. #include <atomic>
  5.  
  6. using namespace std;
  7.  
  8. // Shared variables
  9. atomic<bool> flag0(false); // Flag for process 0
  10. atomic<bool> flag1(false); // Flag for process 1
  11. atomic<int> turn(0); // Variable for turn-based coordination
  12.  
  13. void process(int id) {
  14. int other = 1 - id; // Determine the other process
  15.  
  16. for (int i = 0; i < 3; ++i) { // Run the process three times
  17. // Request to enter critical section
  18. if (id == 0) {
  19. flag0 = true; // Mark process 0 as requesting critical section
  20. turn = 1; // Give turn to process 1
  21. } else {
  22. flag1 = true; // Mark process 1 as requesting critical section
  23. turn = 0; // Give turn to process 0
  24. }
  25.  
  26. // Wait until the other process exits critical section
  27. while ((id == 0 && flag1 && turn == 1) || (id == 1 && flag0 && turn == 0)) {
  28. // Busy wait (not ideal, but needed for mutual exclusion)
  29. }
  30.  
  31. // Critical Section
  32. cout << "Process " << id << " is in critical section" << endl;
  33. this_thread::sleep_for(chrono::seconds(1)); // Simulate work in the critical section
  34.  
  35. // Exit critical section
  36. if (id == 0) {
  37. flag0 = false; // Reset flag for process 0
  38. } else {
  39. flag1 = false; // Reset flag for process 1
  40. }
  41.  
  42. cout << "Process " << id << " is in remainder section" << endl;
  43. this_thread::sleep_for(chrono::milliseconds(500)); // Simulate work in the remainder section
  44. }
  45. }
  46.  
  47. int main() {
  48. // Create two threads representing two processes
  49. thread t1(process, 0);
  50. thread t2(process, 1);
  51.  
  52. // Start both threads (they start automatically upon creation)
  53. // Wait for threads to complete
  54. t1.join();
  55. t2.join();
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 2.99s 5292KB
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