Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<pthread.h>
  4.  
  5. void *func(int n);
  6. pthread_t philosopher[5];
  7. pthread_mutex_t chopstick[5];
  8.  
  9. int main()
  10. {
  11. int i;
  12. void *msg;
  13. for(i=1;i<=5;i++)
  14. {
  15. pthread_mutex_init(&chopstick[i],NULL);
  16. }
  17. for(i=1;i<=5;i++)
  18. {
  19. pthread_create(&philosopher[i],NULL,(void *)func,(int *)i);
  20. }
  21. for(i=1;i<=5;i++)
  22. {
  23. pthread_join(philosopher[i],&msg);
  24. }
  25. for(i=1;i<=5;i++)
  26. {
  27. pthread_mutex_destroy(&chopstick[i]);
  28. }
  29. return 0;
  30. }
  31.  
  32. void *func(int n)
  33. {
  34. printf ("\nPhilosopher %d is thinking ",n);
  35. pthread_mutex_lock(&chopstick[n]);//when philosopher 5 is eating he takes fork 1 and fork 5
  36. pthread_mutex_lock(&chopstick[(n+1)%5]);
  37. printf ("\nPhilosopher %d is eating ",n);
  38. sleep(3);
  39. pthread_mutex_unlock(&chopstick[n]);
  40. pthread_mutex_unlock(&chopstick[(n+1)%5]);
  41. printf ("\nPhilosopher %d finished eating ",n);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement