pthreads生产者 - 消费者僵局

时间:2010-11-03 23:57:11

标签: c multithreading pthreads deadlock producer-consumer

我写了以下代码:

void *produce(void* arg)
{
 buffer* buff = (buffer *) arg;
 while (1)
 {
  pthread_mutex_lock(&mutex);
  if (elements_produced == JOB_SIZE)
  {
   pthread_mutex_unlock(&mutex);
   pthread_exit(NULL);
  }
  elements_produced++;

  while (buff->in_buff == CAPACITY)
  {
   pthread_cond_wait(&cond_empty, &mutex);
  }

  // produce
  buff->buffer[buff->tail] = rand();
  sum_produced += buff->buffer[buff->tail];
  printf(">produced %d\n", buff->buffer[buff->tail]);

  buff->tail = (buff->tail + 1) % CAPACITY;
  buff->in_buff++;
  pthread_cond_signal(&cond_empty);
  pthread_mutex_unlock(&mutex);
 }
 pthread_exit(NULL);
}

void *consume(void* arg)
{
 int rc;
 buffer* buff = (buffer *) arg;
 while (1)
 { 
  rc = pthread_mutex_lock(&mutex);

  if (elements_consumed == JOB_SIZE)
  {
   pthread_mutex_unlock(&mutex);
   pthread_exit(NULL);
   return 0;
  }
  elements_consumed++;

  while (buff->in_buff == 0)
  {   
   rc = pthread_cond_wait(&cond_empty, &mutex);
  }

  // consume  
  printf("<consumed %d\n", buff->buffer[buff->head]);
  sum_consumed += buff->buffer[buff->head];
  buff->head = (buff->head + 1) % CAPACITY;
  buff->in_buff--;
  pthread_cond_signal(&cond_full);
  pthread_mutex_unlock(&mutex);
 }
 pthread_exit(NULL);
 return 0;
}

所有变量都已正确初始化。任务是生成JOB_SIZE元素并使用它们。它不时陷入死锁。我对posix线程很陌生,所以我可能遗漏了一些非常明显的东西(在java / C#/ python中多次生产者/消费者,但现在我真的被卡住了)。我知道使用信号量更容易,但我需要这样做。

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

你在两边使用cond_empty进行等待。你发信号(但从不等待)cond_full。