Guest User

Untitled

a guest
Jul 20th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. //用信号量实现哲学家就餐问题
  2. //为了避免死锁,这里采用给哲学家编号,偶数编号哲学家先拿起左边筷子,而奇数编号哲学家以相反的方向拿起筷子
  3. //几个哲学家对应几个线程,每一根筷子的左右两位哲学家是互斥关系,有几个筷子设置几个信号量
  4. //运行可执行文件,可以发现现象不同,并不是12345的顺序吃饭,还是存在竞争,和系统调度有关
  5. #include <stdio.h>
  6. #include <semaphore.h>
  7. #include <pthread.h>
  8.  
  9. #define N 5 //定义哲学家个数
  10. sem_t chopsticks[N];//定义信号量数组
  11.  
  12. //思考吃饭线程,每个哲学家都是这个动作
  13. void * eat_think(void *arg)
  14. {
  15. //获取是几号哲学家
  16. int i = *(int *)arg;
  17. while(1)
  18. {
  19. if(i%2 == 0) //偶数编号哲学家
  20. {
  21. //申请左边筷子
  22. sem_wait(&chopsticks[i]);
  23.  
  24. //申请右边筷子
  25. sem_wait(&chopsticks[(i+1)%N]);//环,比如最后一个哲学家申请的是5号筷子和1号筷子,所以是求余
  26.  
  27. //吃饭
  28. printf("NO.%d is eating\n",i);
  29.  
  30. //释放右边筷子
  31. sem_post(&chopsticks[(i+1)%N]);
  32.  
  33. //释放左边筷子
  34. sem_post(&chopsticks[i]);
  35.  
  36. }
  37. else//奇数编号哲学家
  38. {
  39.  
  40. //申请右边筷子
  41. sem_wait(&chopsticks[(i+1)%N]);//环,比如最后一个哲学家申请的是5号筷子和1号筷子,所以是求余
  42.  
  43. //申请左边筷子
  44. sem_wait(&chopsticks[i]);
  45.  
  46. //吃饭
  47. printf("NO.%d is eating\n",i);
  48.  
  49. //释放左边筷子
  50. sem_post(&chopsticks[i]);
  51.  
  52. //释放右边筷子
  53. sem_post(&chopsticks[(i+1)%N]);
  54.  
  55.  
  56. }
  57.  
  58. //思考
  59. sleep(1);
  60. //printf("NO.%d is thinking\n",i);
  61. }
  62. return (void *)0;
  63. }
  64.  
  65.  
  66. int main(int argc, const char *argv[])
  67. {
  68. pthread_t pthreadID[N];
  69. int i;
  70.  
  71. //初始化信号量
  72. for(i=0; i<N; i++)
  73. {
  74. if(sem_init(&chopsticks[i],0,1) != 0)
  75. {
  76. printf("sem_init error\n");
  77. return -1;
  78. }
  79. }
  80.  
  81. //创建哲学家线程
  82. for(i=0; i<N; i++)
  83. {
  84.  
  85. if(pthread_create(&pthreadID[i],NULL,eat_think,(void *)&i) != 0)
  86. {
  87. printf("pthread_create error\n");
  88. return -1;
  89. }
  90. }
  91.  
  92. //回收资源
  93. for(i=0; i<N; i++)
  94. {
  95. pthread_join(pthreadID[i],NULL);
  96. }
  97. return 0;
  98. }
Add Comment
Please, Sign In to add comment