博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
哲学家就餐问题代码
阅读量:6149 次
发布时间:2019-06-21

本文共 2136 字,大约阅读时间需要 7 分钟。

// Test.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include 
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;}

详细分析參考<现代操作系统>相关章节

转载地址:http://nzwfa.baihongyu.com/

你可能感兴趣的文章
Linux 查看iptables状态-重启
查看>>
amazeui学习笔记一(开始使用2)--布局示例layouts
查看>>
c#中lock的使用(用于预约超出限额的流程)
查看>>
ODI基于源表时间戳字段获取增量数据
查看>>
并发容器之CopyOnWriteArrayList(转载)
查看>>
什么是AAC音频格式 AAC-LC 和 AAC-HE的区别是什么
查看>>
原创:goldengate从11.2升级到12.1.2
查看>>
Quartz
查看>>
正则表达式的语法规则
查看>>
C#一个关于委托和事件通俗易懂的例子
查看>>
类似于SVN的文档内容差异对比工具winmerge
查看>>
Cause: java.sql.SQLException: The user specified as a definer ('root'@'%') does not exist
查看>>
quratz线程
查看>>
execnet: rapid multi-Python deployment
查看>>
windows修改3389端口
查看>>
关于JavaScript词法
查看>>
FreeSwitch中的会议功能(4)
查看>>
【转】adns解析库——域名解析实例(C++、linux)
查看>>
通过Performance Log确定磁盘有性能问题?
查看>>
HDOJ 2828 Lamp DLX反复覆盖
查看>>