代码拉取完成,页面将自动刷新
#include <windows.h>
#include <process.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
using namespace std; //命名空间std内定义的所有标识符都有效
const unsigned int PHILOSOPHER_NUM=5; //哲学家数目
const char THINKING=1; /*标记当前哲学家的状态,1表示等待,2表示得到饥饿,3表示正在吃饭*/
const char HUNGRY=2;
const char DINING=3;
HANDLE hPhilosopher[5]; //定义数组存放哲学家
/*HANDLE(句柄)是windows操作系统中的一个概念。指的是一个核心对象在某一个进程中的唯一索引*/
HANDLE semaphore[PHILOSOPHER_NUM]; // semaphore 用来表示筷子是否可用
HANDLE mutex; // Mutex用来控制安全输出
DWORD WINAPI philosopherProc( LPVOID lpParameter) //返回 DWORD(32位数据)的 API 函数philosopherProc
{
int myid;
char idStr[128];
char stateStr[128];
char mystate;
int ret;
unsigned int leftFork; //左筷子
unsigned int rightFork; //右筷子
myid = int(lpParameter);
itoa(myid, idStr, 10);
WaitForSingleObject(mutex, INFINITE);
cout << "philosopher " << myid << " begin......" << endl;
ReleaseMutex(mutex);
mystate = THINKING; //初始状态为THINKING
leftFork = (myid) % PHILOSOPHER_NUM;
rightFork = (myid + 1) % PHILOSOPHER_NUM;
while (true)
{
switch(mystate)
{
case THINKING:
mystate = HUNGRY; // 改变状态
strcpy(stateStr, "HUNGRY");
break;
case HUNGRY:
strcpy(stateStr, "HUNGRY");
ret = WaitForSingleObject(semaphore[leftFork], 0); // 先检查左筷子是否可用
if (ret == WAIT_OBJECT_0)
{
ret = WaitForSingleObject(semaphore[rightFork], 0); //左筷子可用就拿起,再检查右筷子是否可用
if (ret == WAIT_OBJECT_0)
{
mystate = DINING; // 右筷子可用,就改变自己的状态
strcpy(stateStr, "DINING");
}
else
{
ReleaseSemaphore(semaphore[leftFork], 1, NULL); // 如果右筷子不可用,就把左筷子放下
}
}
break;
case DINING:
// 吃完后把两支筷子都放下
ReleaseSemaphore(semaphore[leftFork], 1, NULL);
ReleaseSemaphore(semaphore[rightFork], 1, NULL);
mystate = THINKING; // 改变自己的状态
strcpy(stateStr, "THINKING");
break;
}
// 输出状态
WaitForSingleObject(mutex, INFINITE);
cout << "philosopher " << myid << " is : " << stateStr << endl;
ReleaseMutex(mutex);
// sleep a random time : between 1 - 5 s
int sleepTime;
sleepTime = 1 + (int)(5.0*rand()/(RAND_MAX+1.0));
Sleep(sleepTime*10);
}
}
int main()
{
int i;
srand(time(0));
mutex = CreateMutex(NULL, false, NULL);
for (i=0; i<PHILOSOPHER_NUM; i++)
{
semaphore[i] = CreateSemaphore(NULL, 1, 1, NULL);
hPhilosopher[i]=CreateThread(NULL,0,philosopherProc,LPVOID(i), CREATE_SUSPENDED,0);
}
for (i=0; i<PHILOSOPHER_NUM; i++)
ResumeThread(hPhilosopher[i]);
Sleep(2000);
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。