fork download
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <unistd.h>
  5.  
  6. sem_t printerSemaphore; // Semaphore for shared printer
  7.  
  8. void* usePrinter(void* arg) {
  9. int id = *((int*)arg);
  10.  
  11. sem_wait(&printerSemaphore); // Wait (P operation)
  12. std::cout << "Process " << id << " is using the printer...\n";
  13. sleep(2); // Simulate using the printer
  14. std::cout << "Process " << id << " is done printing.\n";
  15. sem_post(&printerSemaphore); // Signal (V operation)
  16.  
  17. return nullptr;
  18. }
  19.  
  20. int main() {
  21. pthread_t t1, t2;
  22. int id1 = 1, id2 = 2;
  23.  
  24. sem_init(&printerSemaphore, 0, 1); // Binary semaphore initialized to 1
  25.  
  26. pthread_create(&t1, nullptr, usePrinter, &id1);
  27. pthread_create(&t2, nullptr, usePrinter, &id2);
  28.  
  29. pthread_join(t1, nullptr);
  30. pthread_join(t2, nullptr);
  31.  
  32. sem_destroy(&printerSemaphore);
  33. return 0;
  34. }
  35.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Process 2 is using the printer...
Process 2 is done printing.
Process 1 is using the printer...
Process 1 is done printing.