我写了以下代码:
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 中多次使用,但现在我真的被卡住了)。我知道用信号量来做这件事要容易得多,但我需要用这种方式来做。
有什么建议么?