简单的餐饮哲学家使用pthreads

use*_*367 1 c pthreads dining-philosopher

我正在研究餐饮哲学家计划.然而,我遇到了一个问题,即我的程序在所有哲学家都吃过之前停止了,我不明白为什么.这是我现在的代码:

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

void *func(int n);
pthread_t philosopher[5];
pthread_mutex_t chopstick[5];

int main()
{
     int i;
     void *msg;
     for(i=1;i<=5;i++)
     {
          pthread_mutex_init(&chopstick[i],NULL);
     }
     for(i=1;i<=5;i++)
     {
          pthread_create(&philosopher[i],NULL,(void *)func,(int *)i);
     }
     for(i=1;i<=5;i++)
     {
          pthread_join(philosopher[i],&msg);
     }
      for(i=1;i<=5;i++)
      {
          pthread_mutex_destroy(&chopstick[i]);
      }
     return 0;
}

void *func(int n)
{
     printf ("\nPhilosopher %d is thinking ",n);
     pthread_mutex_lock(&chopstick[n]);//when philosopher 5 is eating he takes fork 1 and fork 5
     pthread_mutex_lock(&chopstick[(n+1)%5]);
     printf ("\nPhilosopher %d is eating ",n);
     sleep(3);
     pthread_mutex_unlock(&chopstick[n]);
     pthread_mutex_unlock(&chopstick[(n+1)%5]);
     printf ("\nPhilosopher %d finished eating ",n);
}
Run Code Online (Sandbox Code Playgroud)

Mah*_*mer 5

我在SLES 11服务器上多次运行问题代码.我没有观察到问题中指出的问题.

不过,您需要更改以下的for()语句:

for(i=1;i<=5;i++)
Run Code Online (Sandbox Code Playgroud)

for(i=0;i<5;i++)
Run Code Online (Sandbox Code Playgroud)

在任何情况下,问题代码中都可能会发生一些变化.(答案没有关键):

  • 虽然声明'func()'返回'void*',但它没有.
  • 函数原型'void*func(int n);' 如果'main()'移动到文件末尾,则可以消除.
  • 没有必要将'&msg'传递给pthread_join()'; 可以传入'NULL',允许完全消除'msg'.

这是我最终得到的代码:

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

pthread_t philosopher[5];
pthread_mutex_t chopstick[5];

void *func(int n)
   {
   printf ("Philosopher %d is thinking\n",n);

   //when philosopher 5 is eating he takes fork 1 and fork 5
   pthread_mutex_lock(&chopstick[n]);
   pthread_mutex_lock(&chopstick[(n+1)%5]);
   printf ("Philosopher %d is eating\n",n);
   sleep(3);
   pthread_mutex_unlock(&chopstick[n]);
   pthread_mutex_unlock(&chopstick[(n+1)%5]);

   printf ("Philosopher %d finished eating\n",n);

   return(NULL);
   }

int main()
   {
   int i;
   for(i=0;i<5;i++)
      pthread_mutex_init(&chopstick[i],NULL);

   for(i=0;i<5;i++)
      pthread_create(&philosopher[i],NULL,(void *)func,(void *)i);

   for(i=0;i<5;i++)
      pthread_join(philosopher[i],NULL);

   for(i=0;i<5;i++)
      pthread_mutex_destroy(&chopstick[i]);

   return 0;
   }
Run Code Online (Sandbox Code Playgroud)