哲学家算法

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>

#define PHILOSOPHER 5
sem_t chopstick[PHILOSOPHER];
sem_t mutex;

void *pro(void *arg)
{
    int num;
    num=*(int *)arg;
    while(1)
    {
        sem_wait(&mutex);
        sem_wait(&chopstick[num]);
        sem_wait(&chopstick[(num+1)%PHILOSOPHER]);
        printf("philosopher %d eat \n",num);
        sem_post(&chopstick[(num+1)%PHILOSOPHER]);
        sem_post(&chopstick[num]);
        sem_post(&mutex);
        sleep(3);
    }
}

int main()
{
    pthread_t philosopher_id[PHILOSOPHER];
    int num=0;
    int arg[PHILOSOPHER];   

    for(int i=0;i<PHILOSOPHER;i++)
    {
        sem_init(&chopstick[i],0,1);
        arg[i]=i;
    }   

    sem_init(&mutex,0,1);

    for(int i=0;i<PHILOSOPHER;i++)
    {
        int thread=pthread_create(&philosopher_id[i],NULL,pro,(void *)&arg[i]);
        if(thread!=0)
        {
            printf("进程创建失败!");
            exit(1);
        }
    }
    for(int i=0;i<PHILOSOPHER;i++)
    {
        pthread_join(philosopher_id[i],NULL);

    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值