//哲学家就餐问题的解法#include<windows.h>#include<process.h>#include<time.h>#include<stdlib.h>#include<stdio.h>#include<iostream>usingnamespacestd;//命名空间std内定义的所有标识符都有效constunsignedintPHILOSOPHER_NUM=5;//哲学家数目constcharTHINKING=1;/*标记当前哲学家的状态,1表示等待,2表示得到饥饿,3表示正在吃饭*/constcharHUNGRY=2;constcharDINING=3;HANDLEhPhilosopher[5];//定义数组存放哲学家/*HANDLE(句柄)是windows操作系统中的一个概念。指的是一个核心对象在某一个进程中的唯一索引*/HANDLEsemaphore[PHILOSOPHER_NUM];//semaphore用来表示筷子是否可用HANDLEmutex;//Mutex用来控制安全输出DWORDWINAPIphilosopherProc(LPVOIDlpParameter)//返回DWORD(32位数据)的API函数philosopherProc{intmyid;charidStr[128];charstateStr[128];charmystate;intret;unsignedintleftFork;//左筷子unsignedintrightFork;//右筷子myid=int(lpParameter);itoa(myid,idStr,10);WaitForSingleObject(mutex,INFINITE);cout<<"philosopher"<<myid<<"begin......"<<endl;ReleaseMutex(mutex);mystate=THINKING;//初始状态为THINKINGleftFork=(myid)%PHILOSOPHER_NUM;rightFork=(myid+1)%PHILOSOPHER_NUM;while(true){switch(mystate){caseTHINKING:mystate=HUNGRY;//改变状态strcpy(stateStr,"HUNGRY");break;caseHUNGRY: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;caseDINING://吃完后把两支筷子都放下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);//sleeparandomtime:between1-5sintsleepTime;sleepTime=1+(int)(5.0*rand()/(RAND_MAX+1.0));Sleep(sleepTime*10);}}intmain(){inti;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);return0;}