Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //用信号量实现哲学家就餐问题
- //为了避免死锁,这里采用给哲学家编号,偶数编号哲学家先拿起左边筷子,而奇数编号哲学家以相反的方向拿起筷子
- //几个哲学家对应几个线程,每一根筷子的左右两位哲学家是互斥关系,有几个筷子设置几个信号量
- //运行可执行文件,可以发现现象不同,并不是12345的顺序吃饭,还是存在竞争,和系统调度有关
- #include <stdio.h>
- #include <semaphore.h>
- #include <pthread.h>
- #define N 5 //定义哲学家个数
- sem_t chopsticks[N];//定义信号量数组
- //思考吃饭线程,每个哲学家都是这个动作
- void * eat_think(void *arg)
- {
- //获取是几号哲学家
- int i = *(int *)arg;
- while(1)
- {
- if(i%2 == 0) //偶数编号哲学家
- {
- //申请左边筷子
- sem_wait(&chopsticks[i]);
- //申请右边筷子
- sem_wait(&chopsticks[(i+1)%N]);//环,比如最后一个哲学家申请的是5号筷子和1号筷子,所以是求余
- //吃饭
- printf("NO.%d is eating\n",i);
- //释放右边筷子
- sem_post(&chopsticks[(i+1)%N]);
- //释放左边筷子
- sem_post(&chopsticks[i]);
- }
- else//奇数编号哲学家
- {
- //申请右边筷子
- sem_wait(&chopsticks[(i+1)%N]);//环,比如最后一个哲学家申请的是5号筷子和1号筷子,所以是求余
- //申请左边筷子
- sem_wait(&chopsticks[i]);
- //吃饭
- printf("NO.%d is eating\n",i);
- //释放左边筷子
- sem_post(&chopsticks[i]);
- //释放右边筷子
- sem_post(&chopsticks[(i+1)%N]);
- }
- //思考
- sleep(1);
- //printf("NO.%d is thinking\n",i);
- }
- return (void *)0;
- }
- int main(int argc, const char *argv[])
- {
- pthread_t pthreadID[N];
- int i;
- //初始化信号量
- for(i=0; i<N; i++)
- {
- if(sem_init(&chopsticks[i],0,1) != 0)
- {
- printf("sem_init error\n");
- return -1;
- }
- }
- //创建哲学家线程
- for(i=0; i<N; i++)
- {
- if(pthread_create(&pthreadID[i],NULL,eat_think,(void *)&i) != 0)
- {
- printf("pthread_create error\n");
- return -1;
- }
- }
- //回收资源
- for(i=0; i<N; i++)
- {
- pthread_join(pthreadID[i],NULL);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment