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* work(void* arg)
  10. {
  11. sem_wait(&mutex);
  12. shared++;
  13. printf("Thread %d entered critical section. Shared = %d\n", *(int*)arg, shared);
  14. sleep(1);
  15. printf("Thread %d leaving critical section.\n", *(int*)arg);
  16. sem_post(&mutex);
  17. return NULL;
  18. }
  19.  
  20. int main()
  21. {
  22. pthread_t t1, t2;
  23. int id1 = 1, id2 = 2;
  24.  
  25. sem_init(&mutex, 0, 1);
  26.  
  27. pthread_create(&t1, NULL, work, &id1);
  28. pthread_create(&t2, NULL, work, &id2);
  29.  
  30. pthread_join(t1, NULL);
  31. pthread_join(t2, NULL);
  32.  
  33. sem_destroy(&mutex);
  34. return 0;
  35. }
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
Thread 2 entered critical section. Shared = 1
Thread 2 leaving critical section.
Thread 1 entered critical section. Shared = 2
Thread 1 leaving critical section.