Advertisement
willtrieagain

Untitled

Oct 10th, 2020
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. sem_t sem;
  2.  
  3. void* thread(void* arg) {
  4. sem_wait(&mutex);
  5. printf("Entering, thread id %ld\n", pthread_self());
  6.  
  7. sleep(4);
  8.  
  9. printf("Exiting, thread id %ld\n", pthread_self());
  10. sem_post(&mutex);
  11. }
  12.  
  13. int main() {
  14. sem_init(&mutex, 0, 2);
  15. pthread_t t1, t2, t3, t4;
  16. pthread_create(&t1, NULL, thread, NULL);
  17. sleep(1);
  18. pthread_create(&t2, NULL, thread, NULL);
  19. sleep(1);
  20. pthread_create(&t3, NULL, thread, NULL);
  21. sleep(1);
  22. pthread_create(&t4, NULL, thread, NULL);
  23. pthread_join(t1, NULL);
  24. pthread_join(t2, NULL);
  25. pthread_join(t3, NULL);
  26. pthread_join(t4, NULL);
  27. sem_destroy(&mutex);
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement