zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    (转)WCF中的REST是什么
    DrpList
    IIS代码管理(1):遍历应用程序池和属性
    rdp,ListBox,Drp
    在.NET中杀死Word,Excel等进程
    IIS代码管理(2):创建应用程序池和属性
    防止用户重复登录
    asp.net2.0的几种自动生成脚本的原理以及应用
    工厂模式new问题
    我们需要什么样的字段类型?
  • 原文地址:https://www.cnblogs.com/wumaiqiti1020/p/13991913.html
Copyright © 2011-2022 走看看