C-多线程-哲学家进餐问题

网易公开课,哲学家进餐问题,VC2010控制台程序

// testVC.cpp : 哲学家进餐问题。
//
#include "stdafx.h"
HANDLE hSemaphoreForks[5]; //5个叉子使用状态
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人
 for(int j=0;j<5;j++)
 {
  Philosophers[j] = j;
  handle[j] = CreateThread(NULL,1,PhilosopherProc,&Philosophers[j], 0, NULL);
 }
 WaitForMultipleObjects(5,handle,TRUE,INFINITE);
 return 0;
}
DWORD _stdcall PhilosopherProc(LPVOID 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);  //休息
 }
 return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值