信号量 哲学家进餐问题

#include 
#include 
#include 


int chopstick[5];
void P(int * a,int * b)
{
    while(1)
    {
        if((*a)>0&&(*b)>0)
        {
            *a = *a - 1;
            *b = *b - 1;
            break;
        }
    }
}


void V(int * a,int * b)
{
    *a = *a + 1;
    *b = *b + 1;
}


void philosopher(int i)
{
    while(1)
    {
        printf("%d思考\n",i+1);
        sleep(1);
        P(chopstick + (i+1)%5,chopstick + i);
        printf("%d进餐\n",i+1);
        sleep(1);
        V(chopstick+i,chopstick+(i+1)%5);
    }
}








int main()
{
    chopstick[0] = 1;
    chopstick[1] = 1;
    chopstick[2] = 1;
    chopstick[3] = 1;
    chopstick[4] = 1;
    pthread_t t1,t2,t3,t4,t0;
    pthread_create(&t0,NULL,(void*)philosopher,0);
    pthread_create(&t1,NULL,(void*)philosopher,1);
    pthread_create(&t2,NULL,(void*)philosopher,2);
    pthread_create(&t3,NULL,(void*)philosopher,3);
    pthread_create(&t4,NULL,(void*)philosopher,4);
    pthread_join(t0,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    pthread_join(t4,NULL);
    return 0;
}

linux环境下加gcc [文件名] -lpthread编译成功,运行时出现错误结果,相邻进程会同时进餐。发现是前一个进程修改之前,后一个在判断,同时修改chopstick数组,把数组某个元素的值该到了-1.所以需要改进。

你可能感兴趣的:(操作系统实验)