fork download
  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<semaphore.h>
  4. sem_t semaphore;
  5. void* process(void* arg) {
  6. sem_wait(&semaphore);
  7. printf("Process %d is in critical section\n", *(int*)arg);
  8. sleep(1); // simulate work
  9. printf("Process %d is leaving critical section\n", *(int*)arg); sem_post(&semaphore);
  10. return NULL;
  11. }
  12. int main() {
  13. pthread_t t1, t2;
  14. int id1 = 1, id2 = 2;
  15. sem_init(&semaphore, 0, 1);
  16. pthread_create(&t1, NULL, process, &id1);
  17. pthread_create(&t2, NULL, process, &id2);
  18. pthread_join(t1, NULL);
  19. pthread_join(t2, NULL);
  20. sem_destroy(&semaphore);
  21. return 0;
  22.  
  23. }
  24.  
  25.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Process 2 is in critical section
Process 2 is leaving critical section
Process 1 is in critical section
Process 1 is leaving critical section