信号量-哲学家进餐问题

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


sem_t chopsticks[5];//chopsticks


void *PhilosopherEating(void *arg){
    int index = *((int *)arg);

    printf("%d\n",index);

    int first=0;
    int second=0;
    int bOdd = index%2;

    if(bOdd ==1){
        first = index -1;
        second = index%5;
    }else{
        first = index;
        second = index -1;
    }

    while (1) {
        sem_wait(&chopsticks[first]);
        sem_wait(&chopsticks[second]);

        //eating
        printf("index :%d ,first:%d ,second:%d eating\n",index,first,second);

        sem_post(&chopsticks[second]);
        sem_post(&chopsticks[first]);

        //think
        sleep(1);

    }


//    pthread_exit(NULL);

}

int main()
{
    printf("Hello World!\n");
    int i=0;
    pthread_t thread[5];
    int index[5]={1,2,3,4,5};
    for(i = 0 ; i <5 ; i++){
        sem_init(&chopsticks[i],0,1);
    }


    for(i = 0 ; i < 5 ; i++){
        pthread_create(&thread[i],NULL,PhilosopherEating,&index[i]);
    }

    for(i = 0 ; i < 5 ; i++){
        pthread_join(&thread[i],NULL);
    }

    printf("Hello World!\n");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值