哲学家算法c++线程实现

13 篇文章 1 订阅

哲学家算法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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值