#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <semaphore.h>
#include <vector>
using namespace std;
sem_t empty_slot;
sem_t filled_slot;
sem_t locked;
vector<int> num;
void *producer(void *arg){
while(1){
sem_wait(&empty_slot);
sem_wait(&locked);
int data = rand()%10;
num.push_back(data);
int len = num.size();
cout<<"producer:";
for(int i=0; i<len; i++){
cout<<num[i]<<" ";
}
cout<<endl;
sem_post(&filled_slot);
sem_post(&locked);
}
}
void *consumer(void *arg){
while(1){
sem_wait(&filled_slot);
sem_wait(&locked);
int m = num.back();
num.pop_back();
int len = num.size();
cout<<"consumer:";
cout<<m<<" ";
cout<<endl;
sem_post(&empty_slot);
sem_post(&locked);
}
}
int main(){
pthread_t tid1, tid2;
sem_init(&empty_slot,0, 5);
sem_init(&filled_slot,0, 0);
sem_init(&locked,0, 1);
pthread_create(&tid2,NULL,consumer,NULL);
pthread_create(&tid1,NULL,producer, NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&empty_slot);
sem_destroy(&filled_slot);
sem_destroy(&locked);
return 0;
}
|