计算机操作系统_哲学家就餐问题_C++实现源代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//哲学家就餐问题的解法
#include <windows.h>
#include <process.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.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_M
AX+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;
}