資源簡(jiǎn)介
C語(yǔ)言解決哲學(xué)家就餐問(wèn)題
代碼片段和文件信息
//copyright?software?school?Lijianeng???student?ID:12330163
//The?Dinning?Philosophers?Problem?using?win32?API?
#include?
#include?
#include?
#include?
#include?
using?namespace?std;
HANDLE?chop[5]room;
void?init()?{
for(int?i=0;i<5;i++)?{
chop[i]=CreateSemaphore(NULL11NULL);//信號(hào)量初始化?
}
room=CreateSemaphore(NULL44NULL);
}
DWORD?WINAPI?dinning(LPVOID?param)?{
int?num?=?*(int*)param;
while(1)?{
srand(time(0));
if(rand()%2)?{
printf(“%d號(hào)哲學(xué)家決定吃飯\n“num+1);
WaitForSingleobject(roomINFINITE);
WaitForSingleobject(chop[num]INFINITE);?//按照題意需要等到有空余的筷子才吃飯?
printf(“%d號(hào)哲學(xué)家拿起了左邊的%d號(hào)筷子\n“num+1num+1);//critical?section
WaitForSingleobject(chop[(num+1)%5]INFINITE);
printf(“%d號(hào)哲學(xué)家拿起了右邊的
評(píng)論
共有 條評(píng)論