gpt4 book ai didi

c - pthreads生产者消费者死锁

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:57 26 4
gpt4 key购买 nike

我写了下面的代码:

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 中多次使用,但现在我真的被卡住了)。我知道用信号量来做这件事要容易得多,但我需要用这种方式来做。

有什么建议吗?

最佳答案

你在两边都使用了 cond_empty 来等待。您发出信号(但从不等待)cond_full。

关于c - pthreads生产者消费者死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4092751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com