您的位置:首页 > 运维架构 > Linux

linux多线程-哲学家就餐问题

2013-09-24 17:32 295 查看
有可能出现死锁现象
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int chop[5];
pthread_mutex_t  mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_chop[5];

void *philosopher(void *p)
{
const int a = (int)p;   //const int a = *(int *)p;
int i;
printf("thread num = %d, p= %d",a,p);
while(1)
{
i = (a+1) % 5;
printf("num is %d\n",i);
usleep(rand % 10);
pthread_mutex_lock(&mutex);
while(chop[a] == 1)
{
pthread_cond_wait(&cond_chop[a],&mutex);
}
chop[a] = 1;
printf("Philosopher %c fetches chopstick %d\n",'A'+a,a);
while(chop[i] == 1)
pthread_cond_wait(&cond_chop[i], &mutex);
chop[i] = 1;
printf("Philosopher %c fetches chopstick %d\n",'A'+a,i);

pthread_mutex_unlock(&mutex);
usleep(rand() % 10);
pthread_mutex_lock(&mutex);
printf("Philosopher %c releases chopsticks %d %d\n",'A'+a,a,i);
chop[a] = 0;
pthread_cond_signal(&cond_chop[a]);
chop[i] = 0;
pthread_cond_signal(&cond_chop[i]);
pthread_mutex_unlock(&mutex);

}
}

int main()
{
int i;
pthread_t pid[5];
for(i=0; i<5;i++)
{
chop[i] = 0;
pthread_cond_init(&cond_chop[i],NULL);
}
/*最开始写成这样会造成主线程和其他子线程不同步。因为把i的指针当做参数传递过去,循环最后i=5,有可能
philosopher函数中a还未复制,造成不同步。
for(i=0; i<5;i++)
pthread_create(&pid[0], NULL, philosopher, &i);
*/
pthread_create(&pid[0], NULL ,philosopher, 0);
pthread_create(&pid[1], NULL ,philosopher, 1);
pthread_create(&pid[2], NULL ,philosopher, 2);
pthread_create(&pid[3], NULL ,philosopher, 3);
pthread_create(&pid[4], NULL ,philosopher, 4);
pthread_join(pid[0], NULL);
pthread_join(pid[1], NULL);
pthread_join(pid[2], NULL);
pthread_join(pid[3], NULL);
pthread_join(pid[4], NULL);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: