互斥锁中的死锁,条件变量代码



我正在读AS TANENBAUM的《现代操作系统》一书,它给出了一个解释条件变量的例子,如下所示。在我看来,这是一个僵局,不确定我错过了什么。

假设使用者线程首先启动。在锁定_mutex之后,使用者线程被阻塞,等待条件变量condc

如果生产者此时正在运行,_mutex仍将被锁定,因为消费者从未释放它。因此生产商也将被阻止。

在我看来,这是一个教科书式的僵局问题。我错过什么了吗?Thx

#include <stdio.h>
#include <pthread.h>
#define MAX 10000000000         /* Numbers to produce */
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;

void* consumer(void *ptr) {
  int i;
  for (i = 1; i <= MAX; i++) {
    pthread_mutex_lock(&the_mutex); /* lock mutex */
    /*thread is blocked waiting for condc */
    while (buffer == 0) pthread_cond_wait(&condc, &the_mutex);
    buffer = 0;
    pthread_cond_signal(&condp);    
    pthread_mutex_unlock(&the_mutex);
  }
  pthread_exit(0);
}
void* producer(void *ptr) {
  int i;
  for (i = 1; i <= MAX; i++) {
    pthread_mutex_lock(&the_mutex); /* Lock mutex */
    while (buffer != 0) pthread_cond_wait(&condp, &the_mutex);
    buffer = i;
    pthread_cond_signal(&condc);    
    pthread_mutex_unlock(&the_mutex);   
  }
  pthread_exit(0);
}
int main(int argc, char **argv) {
  pthread_t pro, con;
  //Simplified main function, ignores init and destroy for simplicity
  // Create the threads
  pthread_create(&con, NULL, consumer, NULL);
  pthread_create(&pro, NULL, producer, NULL);
}

当您等待一个条件变量时,在等待期间会释放关联的互斥体(这就是将互斥体传递给pthread_cond_wait的原因)。

当pthread_cond_wait返回时,互斥对象总是再次被锁定。

记住这一点,您可以遵循示例的逻辑。

最新更新