生产者消费者模型

生产者消费者模型

一个交易场所,两个对象,三种关系。

消费者与消费者:互斥
生产者与生产者:互斥
生产者与消费者:同步且互斥

下面是一个三个生产者与三个消费者的模型:

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

#define CONSUMER_COUNT 3
#define PRODUCER_COUNT 3

struct msg
{
    struct msg* Next;
    int num;
};
struct msg* head=NULL;

pthread_cond_t cond;
pthread_mutex_t mutex;
pthread_t threads[CONSUMER_COUNT+PRODUCER_COUNT];

void* consumer(void* arg)
{
    int num= *(int*)arg;
    free(arg);
    struct msg* mp;
    while(1)
    {
        pthread_mutex_lock(&mutex);
        while(head==NULL)
        {
            printf("%d begin wait a condition ...\n",num);
            pthread_cond_wait(&cond,&mutex);
        }
        printf("%d exit wait a condition ...\n",num);
        printf("%d begin consume a product ...\n",num);
        mp=head;
        head=mp->Next;
        pthread_mutex_unlock(&mutex);
        printf("Consume %d\n",mp->num);
        free(mp);
        printf("%d end consume product ...\n",num);
        //sleep(5);
    }
}

void* producer(void* arg)
{
    int num=*(int*)arg;
    free(arg);

    struct msg* mp;
    while(1)
    {
        printf("%d begin produce product ...\n",num);
        mp=(struct msg*)malloc(sizeof(struct msg));
        mp->num=rand()%100+1;
        printf("produce %d\n",mp->num);
        pthread_mutex_lock(&mutex);
        mp->Next=head;
        head=mp;
        printf("%d end produce product ...\n",num);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
        sleep(7);
    }
}

int main()
{
    srand(time(NULL));

    pthread_cond_init(&cond,NULL);
    pthread_mutex_init(&mutex,NULL);

    int i;
    for(i=0;i<CONSUMER_COUNT;i++)
    {
        int* p=(int*)malloc(sizeof(int));
        *p=i;
        pthread_create(&threads[i],NULL,consumer,(void*)p);
    }

    for(i=0;i<PRODUCER_COUNT;i++)
    {
        int* p=(int*)malloc(sizeof(int));
        *p=i;
        pthread_create(&threads[CONSUMER_COUNT+i],NULL,producer,(void*)p);
    }

    for(i=0;i<CONSUMER_COUNT+PRODUCER_COUNT;i++)
    {
        pthread_join(threads[i],NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值