互斥体中的死锁,条件变量代码?
Dead lock in the mutex, condition variable code?
我正在阅读 AS TANENBAUM 的现代操作系统一书,它给出了一个解释条件变量的示例,如下所示。在我看来,这是一个僵局,不确定我错过了什么。
让我们假设 consumer 线程首先启动。在 the_mutex 被锁定后, consumer 线程被阻塞等待条件变量, condc.
如果此时producer是运行,the_mutex仍然会被锁定,因为consumer 从不释放它。所以producer也会被屏蔽
在我看来,这是教科书式的死锁问题。我在这里错过了什么吗?感谢
#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 returns时,互斥总是再次被锁定。
牢记这一点,您可以按照示例的逻辑进行操作。
我正在阅读 AS TANENBAUM 的现代操作系统一书,它给出了一个解释条件变量的示例,如下所示。在我看来,这是一个僵局,不确定我错过了什么。
让我们假设 consumer 线程首先启动。在 the_mutex 被锁定后, consumer 线程被阻塞等待条件变量, condc.
如果此时producer是运行,the_mutex仍然会被锁定,因为consumer 从不释放它。所以producer也会被屏蔽
在我看来,这是教科书式的死锁问题。我在这里错过了什么吗?感谢
#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 returns时,互斥总是再次被锁定。
牢记这一点,您可以按照示例的逻辑进行操作。