开张hoho,贴个小程序

以下代码参考《现代操作系统》英文第2版P127哲学家就餐问题例子程序,在windowsXP下使用VC6.0进行了实现,希望大家多提改正意见:

#include "windows.h"

#include <stdio.h>
#include <stdlib.h>

#define PHILO_NUM 5     /* how many philosophers */
#define THINKING 0
#define HUNGRY  1
#define EATING  2
#define DELAY_THINK 500
#define DELAY_EAT 400
#define STRING_LEN 7
#define LEFT(i)  (i+PHILO_NUM-1)%PHILO_NUM
#define RIGHT(i) (i+1)%PHILO_NUM

typedef struct
{
 int i;
}INTEGER;

/* global variables */
int state[PHILO_NUM];
HANDLE h_mutex;       /* Semaphore for exclusion */
HANDLE h_s[PHILO_NUM];     /* Semaphore for philosophers */

/* definition */
void philosopher(void* id)
{

 DWORD wait_for_mutex;
 DWORD wait_for_self;
 int nid;

 nid = ((INTEGER*) id)->i;
 while(TRUE)
 {
  printf("Philosopher%d is thinking.../n", nid);
  Sleep(DELAY_THINK);
  /* He wants to eat. */
  wait_for_mutex = WaitForSingleObject(h_mutex, -1);
  state[nid] = HUNGRY;
  if (state[nid] == HUNGRY && state[LEFT(nid)] != EATING && state[RIGHT(nid)] != EATING)
  {
   state[nid] = EATING;
   ReleaseSemaphore(h_s[nid], 1, NULL);
  }
  ReleaseMutex(h_mutex);
  wait_for_self = WaitForSingleObject(h_s[nid], -1);
  
  printf("Philosopher%d is eating.../n", nid);
  Sleep(DELAY_EAT);
  /* He finishes eating. */
  wait_for_mutex = WaitForSingleObject(h_mutex, -1);
  state[nid] = THINKING;
  if (state[LEFT(nid)] == HUNGRY && state[LEFT(LEFT(nid))] != EATING && state[RIGHT(LEFT(nid))] != EATING)
  {
   state[LEFT(nid)] = EATING;
   ReleaseSemaphore(h_s[LEFT(nid)], 1, NULL);
  }
  if (state[RIGHT(nid)] == HUNGRY && state[LEFT(RIGHT(nid))] != EATING && state[RIGHT(RIGHT(nid))] != EATING)
  {
   state[RIGHT(nid)] = EATING;
   ReleaseSemaphore(h_s[RIGHT(nid)], 1, NULL);
  }
  ReleaseMutex(h_mutex);
 }
}


int main(void)
{
 DWORD thread_ID;
 DWORD wait_for_all;
 HANDLE h_thread[PHILO_NUM];
 INTEGER intNums[PHILO_NUM];

 int i;
 char str_name[STRING_LEN];

 /* initializing... */
 h_mutex = CreateMutex(NULL, FALSE, "mutex_for_state_array");
 h_mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "mutex_for_state_array");

 memset(str_name, 0, STRING_LEN * sizeof(char));
 for (i = 0; i < PHILO_NUM; i++)
 {
  sprintf(str_name, "philo%d", i);
  h_s[i] = CreateSemaphore(NULL, 0, 1, str_name);
  h_s[i] = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, str_name);
 }

 for (i = 0; i < PHILO_NUM; i++)
 {
  intNums[i].i = i;
  h_thread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)(philosopher), &intNums[i], 0, &thread_ID);
 }

 wait_for_all = WaitForMultipleObjects(PHILO_NUM, h_thread, TRUE, -1);
 return 0;
}

阅读更多
想对作者说点什么? 我来说一句

开张志喜

kkkksunday kkkksunday

2005-06-22 10:01:00

阅读数:709

HoHo游戏引擎源代码

2010年04月24日 1.67MB 下载

NOIP 2012 摆花

题目分析

Orion_Rigel Orion_Rigel

2016-11-02 20:44:03

阅读数:329

asp大马(黑客HOHO

2008年09月16日 32KB 下载

没有更多推荐了,返回首页

不良信息举报

开张hoho,贴个小程序

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭