哲学家进餐问题的c语言代码

#include <pthread.h>
#include <stdio.h>

#define N 5
#define LEFT (i+N-1)%N
#define RIGHT (i+1)%N
#define THINK_TIME 3
#define EAT_TIME 2

enum { THINKING, HUNGRY, EATING } state[N];

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER, s[N];

void test(int i)
{
    if (state[i] == HUNGRY
     && state[LEFT] != EATING
     && state[RIGHT] != EATING)
    {
        state[i] = EATING;
        pthread_mutex_unlock(&s[i]);
    }
}

void take_forks(int i)
{
    pthread_mutex_lock(&mutex);
    state[i] = HUNGRY;
    test(i);
    pthread_mutex_unlock(&mutex);
    pthread_mutex_lock(&s[i]);
}

void put_forks(int i)
{
    pthread_mutex_lock(&mutex);
    state[i] = THINKING;
    test(LEFT);
    test(RIGHT);
    pthread_mutex_unlock(&mutex);
}

void think(int i)
{
    printf("philosopher %d is thinking...\n", i);
    sleep(THINK_TIME);
}

void eat(int i)
{
    printf("philosopher %d is eating...\n", i);
    sleep(EAT_TIME);
}

void* phi(void* vargp)
{
    int i = *(int*)vargp;
    while (1)
    {
        think(i);
        take_forks(i);
        eat(i);
        put_forks(i);
    }
    return NULL;
}

int main()
{
    int i;
    pthread_t tid[N];
    for (i = 0; i < N; i++)
        pthread_create(&tid[i], NULL, phi, (void*)(&i));
    for (i = 0; i < N; i++)
        pthread_join(tid[i], NULL);
    return 0;
}

  • 6
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值