#include<iostream>
#include<mutex>
#include<semaphore.h>
#include<pthread.h>
using namespace std;
mutex m;
sem_t empty ;
sem_t full;
int count = 0;
void *produce(void*){
while(true){
sem_wait(&empty);
m.lock();
cout << "生产了第" << ++count << "个产品!" << endl;
m.unlock();
sem_post(&full);
}
}
void* consume(void*){
while(true){
sem_wait(&full);
m.lock();
cout << "消费了一个产品,还剩余" << --count<< "个产品" << endl;
m.unlock();
sem_post(&empty);
}
}
#define P_NUM 8
#define C_NUM 7
#define BUFFER_SIZE 20
int main(){
pthread_t producers[P_NUM];
pthread_t consumers[C_NUM];
int ini1 = sem_init(&empty,0,BUFFER_SIZE);
int ini2 = sem_init(&full,0,0);
if(ini1 != 0 && ini2 != 0){
cout << "sem init failed!" << endl;
return -1;
}
for(int i = 0;i < P_NUM;i++){
pthread_create(&producers[i],NULL,produce,NULL);
}
for(int i = 0;i < C_NUM;i++){
pthread_create(&consumers[i],NULL,consume,NULL);
}
for(int i = 0;i < P_NUM;i++){
pthread_join(producers[i],NULL);
}
for(int i = 0;i < C_NUM;i++){
pthread_join(consumers[i],NULL);
}
return 0;
}