生产者消费者模型
一个交易场所,两个对象,三种关系。
消费者与消费者:互斥
生产者与生产者:互斥
生产者与消费者:同步且互斥
下面是一个三个生产者与三个消费者的模型:
#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;
}