⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tongbujincheng.txt

📁 操作系统的进程,让你自己发挥想象,合理分配空间,简单的很
💻 TXT
字号:
 #include   <windows.h>   
  #include   <stdio.h>   
  #include   <stdlib.h>   
    
  #define   N   4   /*   哲学家的个数   */   
  #define   P(S)   WaitForSingleObject(S,   INFINITE)   //   定义Windows下的P操作   
  #define   V(S)   ReleaseSemaphore(S,   1,   NULL)     //   定义Windows下的V操作   
    
  typedef   HANDLE   Semaphore;   //   信号量的Windows原型   
  HANDLE     hThread[N];           //   线程计数   
  Semaphore   S[N];                   //   N根筷子,   N个信号量   
    
    
  //   对每个哲学家的线程   
  DWORD   WINAPI   Philosopher(LPVOID   para)   
  {   
  //   i表示第i个哲学家   
  int   i   =   *(int   *)para,   j;   
  int   period   =   10   *   (i+1);   
    
  //   j只是用来打印缩进用   
  char   s[10]   =   "";   
  for   (j=0;   j<i;   j++)   strcat(s,   "\t\t");   
    
  while   (   1   )   
  {   
  printf("%s%03d:   think...\n",   s,   i);   
  Sleep(1*period);   
    
  printf("%s%03d:   Hungry\n",   s,   i);   
    
  Sleep(2*period);   
  printf("%s%03d:   Get   %d   ...\n",   s,   i,   i);   
  P(S[i]);   
  printf("%s%03d:   Got   %d   OK\n",   s,   i,   i);   
    
  Sleep(period);   
    
  printf("%s%03d:   Get   %d   ...\n",   s,   i,   (i+1)%N);   
  P(S[(i+1)%N]);   
  printf("%s%03d:   Got   %d   OK\n",   s,   i,   (i+1)%N);     
    
  printf("%s%03d:   Eating   ...\n",   s,   i);   
  Sleep(2*period);   
  printf("%s%03d:   Eaten.\n",   s,   i);   
    
  printf("%s%03d:   Put   down   %d\n",   s,   i,   i);   
  V(S[i]);   
    
  printf("%s%03d:   Put   down   %d\n",   s,   i,   (i+1)%N);   
  V(S[(i+1)%N]);   
    
  printf("\n");   
  }   
  return   0;   
  }   
  int   main(int   argc,   char   *argv[])   
  {   
  DWORD   tid;   
  int   i=0;   
  char   sTmp[32];   
    
  //   初始化信号量   
  for   (i=0;   i<N;   i++)   
  {   
  wsprintf(sTmp,   "chopsticks=%d",   i);   
  S[i]   =   CreateSemaphore(NULL,   1,   1,   sTmp);   
  if   (   !S[i]   )   
  {   
  printf("Create   S   Error!\n");   
  return   -1;   
  }   
  }   
    
  //   开启5个哲学家线程   
  for   (i=0;   i<N;   i++)   
  {   
  hThread[i]   =   CreateThread(NULL,   0,   Philosopher,   &i,   0,   &tid);   
  if   (   hThread[i]   )   WaitForSingleObject(hThread[i],   100);   
  }   
    
  //   等待哲学家执行   
  WaitForMultipleObjects(N,   hThread,   TRUE,   INFINITE);   
  return   0;   
  }   

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -