#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<vector>
#include<queue>
//临界资源
int num=0;
//缓冲区最大值
int MAX_BUF=100;
//定义条件变量
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
//定义互斥量
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void* producer(void*){
while(true){
pthread_mutex_lock(&mutex);
while(num>=MAX_BUF){
//等待
pthread_cond_wait(&cond, &mutex);
printf("缓冲区满了,等待消费者消费\n");
}
num+=1;
printf("生产一个产品,当前产品数量为:%d", num);
sleep(1);//生产产品所需时间
//通知可能等待的消费者
pthread_cond_signal(&cond);
printf("通知消费者...\n");
//解锁
pthread_mutex_unlock(&mutex);
sleep(1);生产产品的频率
}
}
void* consumer(void*){
while(true){
pthread_mutex_lock(&mutex);
while(num<=0){
//等待
pthread_cond_wait(&cond, &mutex);
printf("缓冲区空了,等待生产者生产\n");
}
num-=1;
printf("消费一个产品,当前产品数量为:%d", num);
sleep(1);
//通知可能等待的生产者
pthread_cond_signal(&cond);
printf("通知生产者...\n");
//解锁
pthread_mutex_unlock(&mutex);
}
}
int main()
{
//定义两个线程
pthread_t thread1,thread2;
//一个执行生产者逻辑,一个执行消费者逻辑
pthread_create(&thread1, NULL, &producer, NULL);
pthread_create(&thread2, NULL, &consumer, NULL);
pthread_join(&thread1, NULL);
pthread_join(&thread2, NULL);
return 0;
}
评论