网易公开课,哲学家进餐问题,VC2010控制台程序
// testVC.cpp : 哲学家进餐问题。
//
//
#include "stdafx.h"
HANDLE hSemaphoreForks[5]; //5个叉子使用状态
HANDLE hSemaphoreNumEat; //可以同时进餐的哲学家数量
DWORD _stdcall PhilosopherProc(LPVOID lpParameter);
HANDLE hSemaphoreNumEat; //可以同时进餐的哲学家数量
DWORD _stdcall PhilosopherProc(LPVOID lpParameter);
int main(int argc, char* argv[])
{
HANDLE handle[5];
int Philosophers[5];
for(int i=0;i<5;i++)
hSemaphoreForks[i] = CreateSemaphore(NULL, 1, 1, NULL); //初始化叉子信号量
hSemaphoreNumEat = CreateSemaphore(NULL, 4, 4, NULL); //初始化同时进餐的哲学家数量为4人
{
HANDLE handle[5];
int Philosophers[5];
for(int i=0;i<5;i++)
hSemaphoreForks[i] = CreateSemaphore(NULL, 1, 1, NULL); //初始化叉子信号量
hSemaphoreNumEat = CreateSemaphore(NULL, 4, 4, NULL); //初始化同时进餐的哲学家数量为4人
for(int j=0;j<5;j++)
{
Philosophers[j] = j;
handle[j] = CreateThread(NULL,1,PhilosopherProc,&Philosophers[j], 0, NULL);
}
{
Philosophers[j] = j;
handle[j] = CreateThread(NULL,1,PhilosopherProc,&Philosophers[j], 0, NULL);
}
WaitForMultipleObjects(5,handle,TRUE,INFINITE);
return 0;
}
return 0;
}
DWORD _stdcall PhilosopherProc(LPVOID lpParameter)
{
int id = *(int *)lpParameter;
{
int id = *(int *)lpParameter;
for(int i=0;i<3;i++){
WaitForSingleObject(hSemaphoreNumEat, INFINITE); //可以吃吗?
WaitForSingleObject(hSemaphoreForks[i], INFINITE); //拿起左边叉子
WaitForSingleObject(hSemaphoreForks[(i+1)%5], INFINITE); //拿起右边叉子
printf("Philosopher %d begin %d times to eat \n",id,i); //开吃
Sleep(1000);
ReleaseSemaphore(hSemaphoreForks[i], 1, NULL); //放下左边叉子
ReleaseSemaphore(hSemaphoreForks[(i+1)%5], 1, NULL); //放下右边叉子
ReleaseSemaphore(hSemaphoreNumEat, 1, NULL); //吃完
Sleep(2000); //休息
}
WaitForSingleObject(hSemaphoreNumEat, INFINITE); //可以吃吗?
WaitForSingleObject(hSemaphoreForks[i], INFINITE); //拿起左边叉子
WaitForSingleObject(hSemaphoreForks[(i+1)%5], INFINITE); //拿起右边叉子
printf("Philosopher %d begin %d times to eat \n",id,i); //开吃
Sleep(1000);
ReleaseSemaphore(hSemaphoreForks[i], 1, NULL); //放下左边叉子
ReleaseSemaphore(hSemaphoreForks[(i+1)%5], 1, NULL); //放下右边叉子
ReleaseSemaphore(hSemaphoreNumEat, 1, NULL); //吃完
Sleep(2000); //休息
}
return 0;
}
}