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;
}

                
            
        
浙公网安备 33010602011771号