哲学家就餐问题代码
2015-07-22 09:24
651 查看
// Test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; #define LEFT(n) ((n+4)%5) #define RIGHT(n) ((n+1)%5) class MySemaphore { public: MySemaphore::MySemaphore(long nInitCount) { m_sem = CreateSemaphore(NULL,nInitCount,MAXLONG32,NULL); } bool down(DWORD dwMilliseconds) { if (m_sem) { DWORD dwRet = WaitForSingleObject(m_sem,dwMilliseconds); if (WAIT_OBJECT_0 == dwRet) { return true; } } return false; } bool up() { if (m_sem) { return ReleaseSemaphore(m_sem,1,NULL) ? true : false; } return false; } private: HANDLE m_sem; }; enum PersonState { STATE_THINKING, STATE_WAITING, STATE_EATING, }; MySemaphore personArr[5] = {0,0,0,0,0}; PersonState stateArr[5] = {STATE_THINKING,STATE_THINKING,STATE_THINKING,STATE_THINKING,STATE_THINKING}; MySemaphore mutex = 1; void test(int nIndex) { if (stateArr[nIndex] == STATE_WAITING && stateArr[LEFT(nIndex)] != STATE_EATING&& stateArr[RIGHT(nIndex)] != STATE_EATING) { stateArr[nIndex] = STATE_EATING; personArr[nIndex].up(); } } void take_fork(int nIndex) { mutex.down(INFINITE); stateArr[nIndex] = STATE_WAITING; test(nIndex); mutex.up(); personArr[nIndex].down(INFINITE); } void put_fork(int nIndex) { mutex.down(INFINITE); stateArr[nIndex] = STATE_THINKING; printf("person %d put fork and thinking\n",nIndex+1); test(LEFT(nIndex)); test(RIGHT(nIndex)); mutex.up(); } DWORD WINAPI PersonProc( LPVOID lpParam ) { int nThreadIndex = (int)lpParam; for(;;) { take_fork(nThreadIndex); printf("person %d take fork and eating\n",nThreadIndex+1); Sleep(1000); //eating; put_fork(nThreadIndex); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { HANDLE aThread[5]; for(int i=0; i < 5; i++ ) { aThread[i] = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE) PersonProc, (void*)i, // no thread function arguments 0, // default creation flags NULL); // receive thread identifier if( aThread[i] == NULL ) { printf("CreateThread error: %d\n", GetLastError()); return 1; } } Sleep(-1); return 0; }
具体分析参考<现代操作系统>相关章节
相关文章推荐
- struts 文件上传示例
- Go语言内部rpc简单实例,实现python调用go的jsonrpc小实例
- Spring中四种声明式事务配置
- iis 7 +php验证码不显示的问题
- lambda 表达式 c++
- 全面介绍Windows内存管理机制及C++内存分配实例
- 【SpringMVC整合MyBatis】商品查询工程框架配置
- 不同方式遍历Map集合(全)
- Struts2配置的Param如何调用?
- C++中数组学习要点记录
- Python按照书写顺序输出字典中的元素
- asp.net IsPostBack 简述
- C语言之栈和堆(Stack && Heap)的优缺点及其使用区别
- Python开发环境-Macbook OS X Yosemite上PIL/Pillow的安装
- VS2008调试C++
- Ipython notebook 修改默认工作路径的方法
- 常见网页错误代码大全
- Java正则表达式 Matcher类成员函数 matches find lookingAt group start end 用法
- java学习-------异常
- java 相等测试与继承