使用互斥锁来实现Philosophers的实现

时间:2018-04-01 13:58:35

标签: c multithreading operating-system synchronization

我正在尝试实现DP问题的无死锁实现,但我的实现有时会产生奇怪的结果。比如这一个:

  

5

     

线程4饿了

     

线程4正在吃

     

线程5饿了

     

线程3饿了

     

线程4正在思考

     

线程3正在吃

     

线程5正在吃

     

线程5正在思考

     

线程1饿了

     

线程2饿了

     

线程1正在吃

     

线程3正在思考

     

线程2正在思考

     

线程1正在思考

在这个中,线程(哲学家)2变得饥饿并且开始思考而不进食,即,线程2的拾取函数调用返回,这不应该是这种情况。也许我不明白pthread_cond_wait和pthread_cond_signal是如何工作的。任何帮助赞赏。提前谢谢。

这是我的代码

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
enum state
{ T, H, E };
enum state *st;
pthread_mutex_t mutex, mut, mu;
pthread_cond_t *var;
int n;
void pickup (int philo_num);
void test (int i);
void putdown (int i);
void *philo (int i);
int
main ()
{

  scanf ("%d", &n);
  pthread_t threads[n];
  var = (pthread_cond_t *) malloc (n * sizeof (pthread_cond_t));

  for (int i = 0; i < n; ++i)
    pthread_cond_init (var + i, NULL);

  pthread_mutex_init (&mutex, NULL);
  pthread_mutex_init (&mut, NULL);
  pthread_mutex_init (&mu, NULL);

  st = (enum state *) malloc (n * sizeof (enum state));

  for (int i = 0; i < n; ++i)
    *(st + i) = T;

  for (int i = 0; i < n; ++i)
    pthread_create (&threads[i], NULL, philo, i);

  for (int i = 0; i < n; ++i)
    {
      pthread_join (threads[i], NULL);
    }
  return 0;

}

void
pickup (int philo_num)
{
  pthread_mutex_lock (&mutex);
  *(st + philo_num) = H;
  test (philo_num);

  if (*(st + philo_num) != E)
    pthread_cond_wait (&mutex, (var + philo_num));

  pthread_mutex_unlock (&mutex);
}

void
test (int i)
{
  pthread_mutex_lock (&mut);
  if ((*(st + ((i + n - 1) % n))) != E && (*(st + i) == H)
      && (*(st + ((i + 1) % n))) != E)
    {
      *(st + i) = E;
      printf ("Thread %d is eating\n", i + 1);
      pthread_cond_signal ((var + i));
    }
  pthread_mutex_unlock (&mut);

}

void
putdown (int i)
{
  pthread_mutex_lock (&mu);
  *(st + i) = T;
  printf ("Thread %d is thinking\n", i + 1);
  test ((i + 4) % 5);
  test ((i + 1) % 5);
  pthread_mutex_unlock (&mu);
}




void *
philo (int i)
{
  int j = 0;
  while (j == 0)
    j = rand () % 4;
//      printf("Thread %d is thinking\n",i+1);
  sleep (j);
  printf ("Thread %d is hungary\n", i + 1);
  pickup (i);
  sleep (j);
  putdown (i);
//      printf("Thread %d is thinking\n",i+1);

}

0 个答案:

没有答案