// 解决哲学家就餐问题
// 每个哲学家可用一个线程来模拟。
// 设有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;
}
windows下 c 实现哲学家进餐问题
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 【蝴蝶效应】 蝴蝶效应:上个世纪70年代,美国一个名叫洛伦兹的气象学家在解释空气系统理论时说,亚马逊雨林一只蝴蝶...
- 养成整理并且归类素材的好习惯。 下面这些作品的风格看似归类为复古风。当你要做一个复古风的作品时,就可以从下面这些作...