Guest User

Untitled

a guest
Oct 23rd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <pthread.h>
  7.  
  8. /*
  9. use the pthread flag with gcc to compile this code
  10. ~$ gcc -pthread dining_philosophers.c -o dining_philosophers
  11. */
  12.  
  13. pthread_t *philosophers;
  14. pthread_mutex_t *forks;
  15.  
  16. int philosophers_count;
  17.  
  18.  
  19. void eat(int i){
  20.  
  21. printf("Philosopher %d is eating\n",i+1);
  22.  
  23. sleep(1 + rand()%10);
  24. }
  25.  
  26. void* philosopher(void* args){
  27. int i = 0,first,second;
  28. while(!pthread_equal(*(philosophers+i),pthread_self()) && i < philosophers_count){
  29. i++;
  30. }
  31.  
  32. while(1){
  33.  
  34. printf("Philosopher %d is thinking\n",i+1);
  35.  
  36. sleep(1 + rand()%10);
  37.  
  38. first = i;
  39. second = (i+1)%philosophers_count;
  40.  
  41. pthread_mutex_lock(forks + (first>second?second:first));
  42. pthread_mutex_lock(forks + (first<second?second:first));
  43. eat(i);
  44. pthread_mutex_unlock(forks+first);
  45. pthread_mutex_unlock(forks+second);
  46. }
  47.  
  48. return NULL;
  49. }
  50.  
  51.  
  52. int main(void){
  53. int i,err;
  54.  
  55. srand(time(NULL));
  56.  
  57. printf("Enter number of philosophers:");
  58. scanf("%d",&philosophers_count);
  59. philosophers = (pthread_t*) malloc(philosophers_count*sizeof(pthread_t));
  60. forks = (pthread_mutex_t*) malloc(philosophers_count*sizeof(pthread_mutex_t));
  61.  
  62. for(i=0;i<philosophers_count;++i)
  63. if(pthread_mutex_init(forks+i,NULL) != 0){
  64. printf("Failed initializing fork %d\n",i+1);
  65. return 1;
  66. }
  67.  
  68. for(i=0;i<philosophers_count;++i){
  69. err = pthread_create(philosophers+i,NULL,&philosopher,NULL);
  70.  
  71. if(err != 0){
  72. printf("Error creating philosopher: %s\n",strerror(err));
  73. }else{
  74. printf("Successfully created philosopher %d\n",i+1);
  75. }
  76. }
  77.  
  78. for(i=0;i<philosophers_count;++i)
  79. pthread_join(*(philosophers+i),NULL);
  80.  
  81. free(philosophers);
  82. free(forks);
  83.  
  84. return 0;
  85. }
Add Comment
Please, Sign In to add comment