首页
社区
课程
招聘
[旧帖] [求助]求解此WindowsApi版的哲学家就餐问题是否正确 0.00雪花
发表于: 2012-3-7 18:59 1454

[旧帖] [求助]求解此WindowsApi版的哲学家就餐问题是否正确 0.00雪花

2012-3-7 18:59
1454
代码如下(5个人可以同时使两个人同时就餐,不知道编写的是否正确,求指导Thx!):
//Code By Pnig0s1992
//Date:2012,3,7

#include <stdio.h>
#include <Windows.h>

#define N 5 //设置哲学家总人数
#define LEFT (i+N-1)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2 
#define  MAX_SEM_COUNT 1 //设置最大信号量

HANDLE ghSemaphore;//声明信号量句柄数组
HANDLE SemPhliosopher[N]; //声明哲学家信号量数组
HANDLE aThread[N];//声明线程数组
int state[N];//声明哲学家状态记录数组

CRITICAL_SECTION cs;

VOID take_forks(int i);
VOID put_forks(int i);
VOID tryEat(int i);

VOID WINAPI PhilosopherProc(LPARAM lpParam)
{
  INT PhilosopherNo = (INT)lpParam;
  while(TRUE)
  {
    take_forks(PhilosopherNo);
    put_forks(PhilosopherNo);
  }
}

VOID take_forks(int i)
{
  WaitForSingleObject(ghSemaphore,INFINITE);
  state[i] = HUNGRY;
  tryEat(i);
  ReleaseSemaphore(ghSemaphore,MAX_SEM_COUNT,NULL);
  WaitForSingleObject(SemPhliosopher[i],INFINITE);
}

VOID put_forks(int i)
{
  WaitForSingleObject(ghSemaphore,INFINITE);
  state[i] = THINKING;
  printf("\n%d号哲学家开始思考.",i+1);
  tryEat(LEFT);
  tryEat(RIGHT);
  ReleaseSemaphore(ghSemaphore,MAX_SEM_COUNT,NULL);

}

VOID tryEat(int i)
{
  if(state[i] == HUNGRY && state[LEFT] != EATING && state
 != EATING)
  {
    state[i] == EATING;
    printf("\n\n%d号哲学家正在吃饭.",i+1);
    ReleaseSemaphore(SemPhliosopher[i],MAX_SEM_COUNT,NULL);
  }
}
int main(int argc,char * argv[])
{
  INT index = 0;
  DWORD dwThreadID[N];
  ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,TEXT("Sem"));
  if(ghSemaphore == NULL)
  {
    printf("\n创建信号量失败,请检查。");
    return -1;
  }

  for(index=0;index<N;index++)
  {
    SemPhliosopher[index] = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
    if(SemPhliosopher[index] == NULL)
    {
      printf("\n错误:%d",GetLastError());
      return -1;
    }
  }

  for(index=0;index<N;index++)//为每个哲学家创建一个线程
  {
    aThread[index] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)PhilosopherProc,(LPVOID)index,0,&dwThreadID[index]);
    if(aThread[index] == NULL)
    {
      printf("\n错误:%d",GetLastError());
      return -1;
    }
  }

  WaitForMultipleObjects(N,aThread,TRUE,INFINITE);

  CloseHandle(ghSemaphore);

  for(index=0;index<N;index++)
  {
    CloseHandle(SemPhliosopher[index]);
    CloseHandle(aThread[index]);
  }
        CloseHandle(ghSemaphore);
  return 0;
}

[课程]Android-CTF解题方法汇总!

收藏
免费 0
支持
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回
//