C生产者-消费者关系的实施
在阅读Richard Stevens的《unix环境中的高级编程》时,我试图添加一个关于POSIX pthread接口的生产者-消费者问题的片段,但在实现它时发现了问题。有人能帮助实现以下代码吗C生产者-消费者关系的实施,c,pthreads,C,Pthreads,在阅读Richard Stevens的《unix环境中的高级编程》时,我试图添加一个关于POSIX pthread接口的生产者-消费者问题的片段,但在实现它时发现了问题。有人能帮助实现以下代码吗 #include <stdio.h> #include <pthread.h> struct msg{ int num; struct msg *next; }; struct msg *queue; pthread_cond_t condition =
#include <stdio.h>
#include <pthread.h>
struct msg{
int num;
struct msg *next;
};
struct msg *queue;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void produce(struct msg * temp){
pthread_mutex_lock(&mutex);
temp->next = queue;
queue = temp;
printf("Produce: %d\n", queue->num);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condition);
}
void* consume(void * args){
struct msg * temp;
for(;;){
pthread_mutex_lock(&mutex);
while (queue == NULL) {
pthread_cond_wait(&condition, &mutex);
}
printf("consume: %d\n", queue->num);
temp = queue;
queue = temp->next;
pthread_mutex_unlock(&mutex);
}
}
void* thread_run(void *arg){
int i = 0;
for(; i < 5; i++){
struct msg m = {i + 1};
produce(&m);
}
}
int main(void){
pthread_t p, consumer;
int err = pthread_create(&p, NULL, thread_run, NULL);
if (err != 0){
printf("error on creating thread...\n");
}
err = pthread_create(&consumer, NULL, consume, NULL);
if (err != 0){
printf("error on creating thread...\n");
}
pthread_join(p, NULL);
pthread_join(consumer, NULL);
}
到底是什么不起作用?消费者线程没有打印完整的5个正确数字。我们知道这是最终结果。但是到目前为止你做了什么调试,具体问题是什么?对不起,我是C新手,现在调试有问题,主要问题是使用者锁定了互斥锁,所以制作人将永远坐在互斥锁上等待。建议在头部不为空之前不要锁定互斥锁。作为解决问题的第一步。使用者循环可以忽略head变量,并且是一条等待事件信号的直线,然后进入一个循环,在每个循环中使用一个结构,直到head为null。