本文主要是介绍三个同步与互斥问题之生产者与消费者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<stdio.h>#include<pthread.h>
pthread_mutex_t mutex;
#define Max 10
pthread_cond_t pro;
pthread_cond_t con;
int buffer=0;//全局变量----一开始为0,只有生产者可以执行
void deal_produce(void *arg)
{//消费---
int i;
for(i=1;i<=Max;i++)
{//
pthread_mutex_lock(&mutex);
while(buffer!=0) pthread_cond_wait(&pro,&mutex);//锁住生产者,在有产品的时候
printf("producer produce item :%d\n",i);
buffer=i;
pthread_cond_signal(&con);//通知消费者
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void deal_consume(void *arg)
{//生产
int i;
for(i=1;i<=Max;i++)
{//加锁,消费的时候不准生产
pthread_mutex_lock(&mutex);
while(buffer==0) pthread_cond_wait(&con,&mutex);
printf("consumer consume item :%d\n",i);
buffer=0;//!?buffer--?
if(buffer==0) pthread_cond_signal(&pro);//没货待产
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main()
{
pthread_t consumer,producer;
pthread_mutex_init(&mutex,0);
//0 :NULL
//API :int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr)
pthread_cond_init(&pro,0);
pthread_cond_init(&con,0);
pthread_create(&producer,NULL,&deal_produce,NULL);
pthread_create(&consumer,NULL,&deal_consume,NULL);
pthread_join(consumer);
pthread_join(producer);
pthread_cond_destroy(&pro);
pthread_cond_destroy(&con);
exit(0);
}
这篇关于三个同步与互斥问题之生产者与消费者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!