Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <sys/sem.h>
  4. #include <unistd.h>
  5. #include <stdio.h>
  6. #include <dirent.h>
  7. #include <pthread.h>
  8. #include <time.h>
  9.  
  10. #define EATING 1;
  11. #define THINKING 2;
  12. #define HUNGRY 3;
  13.  
  14. int phNum = 5;
  15. int status[5] = {2, 2, 2, 2, 2};
  16. pthread_mutex_t section;
  17.  
  18. void *philosopher(void *arg) {
  19.     int id = arg;
  20.     int left, right;
  21.     switch (id) {
  22.         case 0:
  23.             left = 1;
  24.             right = 4;
  25.         break;
  26.         case 4:
  27.             left = 0;
  28.             right = 3;
  29.         break;
  30.         default:
  31.                 right = id - 1;
  32.             left = id + 1;
  33.         break;
  34.     }
  35.         while(1)
  36.         {
  37.         printStat();
  38.             think(id);
  39.         printStat();
  40.         while (status[id] != 1) {
  41.             takeForks(id, left, right);
  42.         }
  43.         printStat();
  44.             eat(id);
  45.         printStat();
  46.             putForks(id);
  47.         }
  48.         pthread_exit(NULL);
  49. }
  50.  
  51. int printStat() {
  52.     int i;
  53.     for (i = 0; i < 5; i++) {
  54.             printf("%ld, ", status[i]);
  55.         }
  56.         printf("\n");
  57.         return 0;
  58. }
  59.  
  60. int think(int id) {
  61.     printf("Phil %ld is thinking\n", id);
  62.         sleep(rand() % phNum + 1);
  63.         status[id] = HUNGRY;
  64.         return 0;
  65. }
  66.  
  67. int eat(int id) {
  68.     printf("Phil %ld is eating\n", id);
  69.         sleep(rand() % phNum + 1);
  70.         return 0;
  71. }
  72.  
  73. int takeForks(int id, int left, int right) {
  74.     pthread_mutex_lock(&section);
  75.     if  ((status[left] != 1) && (status[right] != 1)) {
  76.         printf("Phil %ld got forks \n", id, left, right);
  77.         status[id] = EATING;
  78.     }
  79.     pthread_mutex_unlock(&section);
  80.     return 0;
  81. }
  82.  
  83. int putForks(int id) {
  84.         printf("Phil %ld has released forks \n", id);
  85.         status[id] = THINKING;
  86.         return 0;
  87. }
  88.  
  89. int main(int argc, char *argv[]) {
  90.         srand (time(NULL));
  91.         int i;
  92.         for (i = 0; i < phNum; i++) {
  93.             pthread_attr_t * thAttr = NULL;
  94.             pthread_t tid;
  95.             pthread_create(&tid, thAttr, philosopher, (void*)i);
  96.     }
  97.         while(1) {}
  98.         return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement