哲学家算法c++线程实现
调用了很多STL函数
标记了注释
具体实现了五个哲学家就餐的问题 当然 人数可以根据需求改变
#include <windows.h>
#include <process.h>
#include "iostream"
using namespace std;
const unsigned int N= 5; //number of phil
const int THINKING=1; // 1 means full
const int HUNGRY=2; // 2 means hungry
const int DINING=3; // 3 means eating
HANDLE hPhilosopher[N];
HANDLE semaphore[N];
HANDLE mutex; //typedef void* HANDLE, output
DWORD WINAPI philosopherProc(LPVOID lpParameter) //return DWORD( API (32_bit
//typedef unsigned long DWORD
//typedef WINAPI __stdcall 函数参数入栈方式从右到左,一般导出函数时用。
//typedef void* LPVOID
{
char stateStr[128];
int ret;
unsigned int leftFork; // chopsticks
unsigned int rightFork;
int myid = int(lpParameter);
WaitForSingleObject(mutex, INFINITE); // safely output
cout << "philosopher" << myid << " begin" << endl;
ReleaseMutex(mutex);
int mystate = THINKING;
leftFork = (myid)%N;
rightFork = (myid+1)%N;
while(true)
{
switch(mystate) // change
{
case THINKING:
mystate = HUNGRY; //thinking to hungry
strcpy(stateStr, "HUNGRY");
break;
case HUNGRY:
strcpy(stateStr, "HUNGRY");
ret = WaitForSingleObject(semaphore[leftFork], //left first
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(100);
}
}
int main()
{
mutex = CreateMutex(NULL, false, NULL);
for (int i = 0; i < N; i++)
{
semaphore[i] = CreateSemaphore(NULL, 1, 1, NULL);
hPhilosopher[i] = CreateThread(NULL, 0, philosopherProc, LPVOID(i), CREATE_SUSPENDED, 0);
}
for (int i = 0; i < N; i++)
{
ResumeThread(hPhilosopher[i]);
}
Sleep(800);
return 0;
}