5位哲学家吃饭问题(算法描述)

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

/*

设有5个哲学家,共享一张放有5把椅子的桌子,每人分得一把椅子,但是,桌子上共有5只筷子,在每人两边各放一只,哲学家们在肚子饥饿时才试图分两次从两边拿起筷子就餐。

条件:

1)拿到两只筷子时哲学家才开始吃饭。

2)如果筷子已在他人手上,则该哲学家必须等他人吃完之后才能拿到筷子。

3)任一哲学家在自己未拿到两只筷子前却不放下自己手中的筷子。

试:

1)描述一 个保证不会出现两个邻座同时要求吃饭的通信算法。

2)描述一个即没有两个邻座同时吃饭,有没有饿死(永远拿不到筷子)的算法

*/

/* 以下是测试代码 。。。。*/

#include <stdio.h>

#include <stdlib.h>

#define SizeArray 5

typedef struct { int value; }Key;

typedef struct

{

int left;

int right;

int busy;

}Man;

int getkey( int *blpKey, int *blpMan, int *blpBusy )

/* had key return 0 . get key or no key(orther got) return 1 */

{

if( *blpKey )

{

if(*blpMan) { return 0; }

else { return 1; }

}

else

{

*blpMan = 1;

*blpKey = 1;

++(*blpBusy);

return 1;

}

}

Man aMan[SizeArray];

Key aKey[SizeArray];

#define NextAp ((ap+SizeArray+1)%SizeArray)

#define DGetRight(ap,NextAp) getkey( &(aKey[NextAp].value), &(aMan[ap].right), &(aMan[ap].busy))

/*上边的 \不是 / 。。。!*/

#define DGetLeft(ap,NextAp) getkey( &(aKey[NextAp].value), &(aMan[ap].left), &(aMan[ap].busy))

int count;

int main( void )

{

int ap;

int i;

/*for( i=0 ; i < SizeArray ; ++i )

{

aMan[i].left = 0;

aMan[i].right= 0;

aMan[i].busy = 0;

aKey[i].value= 0;

}

*/

/* test 1000 no. */

for( i=0; i<1000; ++i )

{

ap = rand() % SizeArray ; /*SizeArray = 5 ..this */

if ( aMan[ap].busy == 2 ) /* had 2 key ,down all !! */

{

++count; /*record had thing to eating */

aMan[ap].left = 0;

aMan[ap].right= 0;

aMan[ap].busy = 0;

aKey[ap].value = 0;

aKey[NextAp].value = 0;

}

else

{

if( ap % 2 )

{

if ( DGetRight(ap,ap) ) { continue;}

else{ DGetLeft(ap,NextAp) ;continue;}

}

else

{

if ( DGetLeft(ap,NextAp)) { continue;}

else{ DGetRight(ap,ap) ;continue; }

}

}

} /*end for.. */

printf("dream : test = %d : %d ",500,count);

return 0;

} /*end main..*/

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航