生产者消费者---C实现

来源:互联网 发布:sql数据库查询软件 编辑:程序博客网 时间:2024/04/27 06:46

#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>

#define MAX_NODE_NUMBER (1000*10000)

struct node{
    int value;
    struct node * next;
};


volatile struct node *first,*divider,*last;
pthread_mutex_t list_lock;

void producer(void)
{
    int i;
    struct node * new = NULL, *tmp = NULL;
    printf("hi,I am the producer/n");

    for(i=1;i<=MAX_NODE_NUMBER;i++){
        new = malloc(sizeof(struct node));
        if(new == NULL){
            printf("malloc new node error!!!/n");
            return;
        }

        new->value  = i;
        new->next   = NULL;

        pthread_mutex_lock(&list_lock);
        last->next  = new;
        last        = new;
        pthread_mutex_unlock(&list_lock);
    }

    printf("producer exit.../n");
}

void consumer(void)
{
    struct node * tmp;
    printf("hi,I am the consumer/n");

    while(1){
        pthread_mutex_lock(&list_lock);
        if(first!=last){
            if(first->next->value == MAX_NODE_NUMBER){
                pthread_mutex_unlock(&list_lock);
                return;
            }else{
                first->value++;            
                tmp = first;
                first   = first->next;
                free(tmp);
            }
        }
        pthread_mutex_unlock(&list_lock);
    }
}

int main(void)
{
    pthread_t thread[2];
    printf("node number : %d/n",MAX_NODE_NUMBER);
   
    first = divider = last = malloc(sizeof(struct node));
    if(first == NULL){
        printf("malloc first node error!!!/n");
        return;
    }
    first->value    = 0;
    first->next = NULL;

    pthread_mutex_init (&list_lock,NULL);

    if(pthread_create(&thread[0],NULL,(void *)producer,NULL) != 0){
        printf("create producer error/n");
        return -1;
    }

    if(pthread_create(&thread[1],NULL,(void *)consumer,NULL) != 0){
        printf("create producer error/n");
        return -1;
    }

    pthread_join(thread[0],NULL);
    pthread_join(thread[1],NULL);
   
    printf("main thread exiting.../n");
    return 0;
}

原创粉丝点击