php 哲学家进餐,windows下 c 实现哲学家进餐问题

// 解决哲学家就餐问题

// 每个哲学家可用一个线程来模拟。

// 设有5个哲学家,5只筷子,每个哲学家吃饭时间为一个随机值,哲学家吃饭后的思考时间也是一个随机值。

#include

#include

#include

#include

#include

/*

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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值