使用 C 的 pthread 库,我尝试实现一个简单的生产者-消费者模式。
生产者生成随机数并将它们放入这样的队列
typedef struct {
int q[MAX_QUEUE];
int head;
int tail;
} queue;
消费者只需一一获取数字并将其打印到标准输出。同步是通过一个互斥锁和两个条件变量完成的:empty_queue
(如果队列为空,则暂停消费者)和 full_queue
(暂停消费者)生产者(如果队列已满)。问题是两个线程在达到生成/消耗的 MAX_QUEUE 元素时都会自行挂起,因此它们会进入死锁情况。我认为我做的一切都是正确的,我不知道我做错了什么。
制作人:
void* producer(void* args) {
unsigned seed = time(NULL);
int random;
queue *coda = (queue *) args;
while(1) {
Pthread_mutex_lock(&queue_lock);
while(coda->head == MAX_QUEUE-1) { // Full Queue
printf("Suspending producer\n");
fflush(stdout);
Pthread_cond_wait(&full_queue, &queue_lock);
}
random = rand_r(&seed) % 21;
enqueue(coda, random);
Pthread_cond_signal(&empty_queue);
Pthread_mutex_unlock(&queue_lock);
sleep(1);
}
return NULL;
}
消费者:
void* consumer(void* args) {
queue *coda = (queue *) args;
int elem;
while(1) {
Pthread_mutex_lock(&queue_lock);
while(coda->head == coda->tail) { // Empty Queue
printf("Suspending Consumer\n");
fflush(stdout);
Pthread_cond_wait(&empty_queue, &queue_lock);
}
elem = dequeue(coda);
printf("Found %i\n",elem);
Pthread_cond_signal(&full_queue);
Pthread_mutex_unlock(&queue_lock);
}
return NULL;
}
入队/出队例程
static void enqueue(queue *q, int elem) {
q->q[(q->tail)] = elem;
(q->tail)++;
if(q->tail == MAX_QUEUE)
q->tail = 0;
}
static int dequeue(queue *q) {
int elem = q->q[(q->head)];
(q->head)++;
if(q->head == MAX_QUEUE)
q->head = 0;
return elem;
}
Pthread_* 只是标准 pthread_* 库函数的包装函数。 输出(MAX_QUEUE = 10):
Suspending Consumer
Found 16
Suspending Consumer
Found 7
Suspending Consumer
Found 5
Suspending Consumer
Found 6
Suspending Consumer
Found 17
Suspending Consumer
Found 1
Suspending Consumer
Found 12
Suspending Consumer
Found 14
Suspending Consumer
Found 11
Suspending Consumer
Suspending producer
最佳答案
coda->head == MAX_QUEUE-1
这不会检查队列是否已满。有两个变量描述队列的状态:head
和 tail
。
coda->head == coda->tail
这可以正确检查队列是否为空。请注意检查中如何使用这两个变量。
关于c - 生产者-消费者队列中出现奇怪的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36968323/