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

有可能出现死锁现象
#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;
 }   



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值