主题:快开门看看
lpknui
[专家分:0] 发布于 2005-09-27 22:16:00
5个哲学家在一张桌子上一起吃饭,只有5支筷子,每人要能吃到饭,怎样解决吃到饭又不发生死锁
回复列表 (共4个回复)
沙发
calflyok [专家分:220] 发布于 2005-09-27 23:02:00
好像是个例题哦
板凳
lpknui [专家分:0] 发布于 2005-09-27 23:06:00
是习题,没答案啊
3 楼
苦力强 [专家分:430] 发布于 2005-09-29 02:34:00
如果换我我就直接下手去抓饭,免得饿死。
呵呵!开个玩笑而已。以下是解决哲学家温饱问题的源码。
#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 )
{
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..*/
[em1]
4 楼
lpknui [专家分:0] 发布于 2005-10-12 19:18:00
THANK YOU
我来回复