/*
設有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..*/