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

本文共 2242 字,大约阅读时间需要 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;}

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

posted on
2017-04-25 17:23 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/mthoutai/p/6763269.html

你可能感兴趣的文章
在webconfig中写好连接后,在程序中如何调用?
查看>>
限制用户不能删除SharePoint列表中的条目(项目)
查看>>
【Linux网络编程】使用GDB调试程序
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>
Android ListView上拉获取下一页
查看>>
算法练习题
查看>>
学习使用Django一 安装虚拟环境
查看>>
Hibernate视频学习笔记(8)Lazy策略
查看>>
CSS3 结构性伪类选择器(1)
查看>>
IOS 杂笔-14(被人遗忘的owner)
查看>>
自动测试用工具
查看>>
前端基础之BOM和DOM
查看>>
[T-ARA/筷子兄弟][Little Apple]
查看>>