資源簡介
C語言解決哲學家就餐問題
代碼片段和文件信息
//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);//信號量初始化?
}
room=CreateSemaphore(NULL44NULL);
}
DWORD?WINAPI?dinning(LPVOID?param)?{
int?num?=?*(int*)param;
while(1)?{
srand(time(0));
if(rand()%2)?{
printf(“%d號哲學家決定吃飯\n“num+1);
WaitForSingleobject(roomINFINITE);
WaitForSingleobject(chop[num]INFINITE);?//按照題意需要等到有空余的筷子才吃飯?
printf(“%d號哲學家拿起了左邊的%d號筷子\n“num+1num+1);//critical?section
WaitForSingleobject(chop[(num+1)%5]INFINITE);
printf(“%d號哲學家拿起了右邊的
- 上一篇:捷聯慣性導航C語言實現
- 下一篇:營養套餐問題
評論
共有 條評論