c實現哲學家進餐問題。WINDOWS下。


// 解決哲學家就餐問題
// 每個哲學家可用一個線程來模擬。
// 設有5個哲學家,5只筷子,每個哲學家吃飯時間為一個隨機值,哲學家吃飯后的思考時間也是一個隨機值。
#include <Windows.h>
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <time.h>
/*
(1)奇數號的哲學家先拿起右邊的筷子再拿起左邊的筷子。

(2)偶數號哲學家先拿起左邊的筷子,再拿起右邊的筷子。

(3)如果哲學家搶到一只筷子,在搶占另一只筷子時失敗,則要放棄已經搶占到的資源。

(4)左右兩邊都搶到筷子的哲學家,吃完放后釋放資源。*/
using namespace std;

HANDLE chop[5];
HANDLE ph[5];
HANDLE mutex;
int nums=0;

int random()
{
return rand()%100+20;
}
void eating(int id)
{
int num=random();
Sleep(num);
printf("\t\t\t哲學家%d號吃了%d秒\n",id,num);
}

DWORD WINAPI phthread(LPVOID param){
nums++;
int id=nums;
int lc=id-1;
int rc=id%5;
int times=0;
int ret1,ret2;
while(true)
{
Sleep(100);
if (times>=2)
break;
if (id % 2 == 0)
{
ret1 = WaitForSingleObject(chop[lc], 0);
if (ret1 == WAIT_OBJECT_0)
{
ret2 = WaitForSingleObject(chop[rc], 0);
if (ret2 == WAIT_OBJECT_0)
{
WaitForSingleObject(mutex,INFINITE);
printf("哲學家%d號拿到兩只筷子開始吃第%d頓飯。\n", id,times+1);
ReleaseMutex(mutex);
times++;
WaitForSingleObject(mutex,INFINITE);
eating(id);
ReleaseMutex(mutex);
WaitForSingleObject(mutex,INFINITE);
printf("\t\t\t哲學家%d號吃完兩頓飯啦,放下筷子。\n", id);
ReleaseMutex(mutex);
ReleaseSemaphore(chop[rc], 1, NULL);
}
ReleaseSemaphore(chop[lc], 1, NULL);
}
}
else
{
ret1 = WaitForSingleObject(chop[rc], 0);
if (ret1 == WAIT_OBJECT_0)
{
ret2 = WaitForSingleObject(chop[lc], 0);
if (ret2 == WAIT_OBJECT_0)
{
WaitForSingleObject(mutex,INFINITE);
printf("哲學家%d號拿到兩只筷子開始吃%d頓飯。\n", id,times+1);
ReleaseMutex(mutex);
times++;
WaitForSingleObject(mutex,INFINITE);
eating(id);
ReleaseMutex(mutex);
WaitForSingleObject(mutex,INFINITE);
printf("\t\t\t哲學家%d號吃完兩頓飯啦,放下筷子。\n", id);
ReleaseMutex(mutex);
ReleaseSemaphore(chop[lc], 1, NULL);
}
ReleaseSemaphore(chop[rc], 1, NULL);
}
}
WaitForSingleObject(mutex,INFINITE);
ReleaseMutex(mutex);
}
printf("=======哲學家%d吃飽了然后離開了。=======\n",id);
return 0;

}

int main()
{
srand((unsigned)time(0));
mutex = CreateMutex(NULL, false, NULL);
for (int i = 0; i < 5; ++i)
{
chop[i]=CreateSemaphore(NULL,1,1,NULL);
}
for (int i = 0; i < 5; ++i)
{
int j = i + 1;
ph[i] = CreateThread(NULL, 0, phthread,NULL, 0, NULL);
}

 

Sleep(10000);//釋放句柄
for (int i = 0; i < 5; ++i)
{
CloseHandle(ph[i]);
CloseHandle(chop[i]);
}
CloseHandle(mutex);
Sleep(500);
system("pause");
return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM