• 123


    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
    #include<sys/wait.h>

    typedef struct _list
    {
        struct _list *next;
        int _val;
    }product_list;

    product_list *head = NULL;
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t need_product = PTHREAD_COND_INITIALIZER;

    void Init_list(product_list* list)
    {
        if(list != NULL)
        {
            list -> next = NULL;
            list -> _val = 0;
        }
    }

    void* Consumer(void* _val)
    {
        product_list *p = NULL;
        for(;;)
        {
            pthread_mutex_lock(&lock);
            while(head == NULL)
            {
                pthread_cond_wait(&need_product,&lock);
            }
            p = head;
            head = head -> next;
            p -> next = NULL;
            pthread_mutex_unlock(&lock);
            printf("Consum success,val is:%d ",p -> _val);
            free(p);
        }
        return NULL;
    }

    void* Product(void* _val)
    {
        for(;;)
        {
            sleep(rand() % 2);
            product_list* p =malloc(sizeof(product_list));
            pthread_mutex_lock(&lock);
            Init_list(p);
            p -> _val = rand() % 1000;
            p -> next = head;
            head = p;
            pthread_mutex_unlock(&lock);
            printf("Call consumer! Product has producted,val is:%d ",p->_val);
            pthread_cond_signal(&need_product);
        }
    }

    int main()
    {
        pthread_t t_product;
        pthread_t t_consumer;
        pthread_create(&t_product,NULL,Product,NULL);
        pthread_create(&t_consumer,NULL,Consumer,NULL);

        pthread_join(t_product,NULL);
        pthread_join(t_consumer,NULL);
        return 0;
    }

  • 相关阅读:
    经验大奉献。收集您的经验之你用什么方法提高.NET网站的性能!
    [书]:asp.net 2.0 高级编程(微软技术丛书)
    VS 2008 快捷键
    [书]:《Improving ASP.NET Performance》提高系统性能
    [书]:<<软件工程导论>> 听说很好,不知是真的否.
    [转] C#编码好习惯,献给所有热爱c#的同志
    [书]:UML和模式应用
    在后台代码里写 JS语句.
    查看和修改MTU值
    Lucene.NET搜索多个索引文件
  • 原文地址:https://www.cnblogs.com/wumaiqiti1020/p/13991913.html
Copyright © 2020-2023  润新知