生产者 - 消费者的C实现

时间:2015-01-29 16:59:57

标签: 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 = 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);
}

0 个答案:

没有答案