fork(1) download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <unistd.h>
  5.  
  6. sem_t mutex;
  7. int shared = 0;
  8.  
  9. void* critical_section(void* arg)
  10. {
  11. sem_wait(&mutex);
  12. int temp = shared;
  13. temp++;
  14. sleep(1);
  15. shared = temp;
  16. printf("Thread %ld: shared = %d\n", (long)arg, shared);
  17. sem_post(&mutex);
  18. return NULL;
  19. }
  20.  
  21. int main()
  22. {
  23. pthread_t t1, t2;
  24. sem_init(&mutex, 0, 1);
  25.  
  26. pthread_create(&t1, NULL, critical_section, (void*)1);
  27. pthread_create(&t2, NULL, critical_section, (void*)2);
  28.  
  29. pthread_join(t1, NULL);
  30. pthread_join(t2, NULL);
  31.  
  32. sem_destroy(&mutex);
  33. return 0;
  34. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Thread 2: shared = 1
Thread 1: shared = 2