1.h
#include <pthread.h>
#include <vector>
#include <time.h>
using namespace std;
class Apple{
private:
int id;
public:
Apple(int _num);
~Apple();
int get_id();
};
Apple::Apple(int num){
id = num;
}
Apple::~Apple(){
id = 0;
}
int Apple::get_id(){
return id;
}
class Backet{
public:
pthread_mutex_t lock;
pthread_cond_t cond;
vector<Apple*> bat;
Backet();
~Backet();
void push(Apple *ap);
Apple* pop();
};
Backet::Backet(){
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond,NULL);
}
Backet::~Backet(){
}
void Backet::push(Apple *ap){
pthread_mutex_lock(&lock);
bat.push_back(ap);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
Apple* Backet::pop(){
Apple* ap = NULL;
pthread_mutex_lock(&lock);
struct timespec timeout;
timeout.tv_sec = time(0)+1;
timeout.tv_nsec=0;
while(bat.empty()){
pthread_cond_timedwait(&cond,&lock,&timeout);
}
ap = bat.back();
bat.pop_back();
pthread_mutex_unlock(&lock);
return ap;
}
1.cpp
#include <iostream>
#include <unistd.h>
#include "1.h"
Backet bat;
void* consume(void*){
while(1){
//sleep(2);
Apple *a = bat.pop();
cout << "eat apple " << a->get_id() << endl;
delete a;
}
}
void* product(void*){
static int number =0;
while(1){
sleep(4);
number++;
Apple *a = new Apple(number);
cout << "product apple " << a->get_id() << endl;
bat.push(a);
}
}
int main(){
pthread_t t1;
pthread_t t2;
pthread_create(&t1,NULL,consume,NULL);
pthread_create(&t2,NULL,product,NULL);
pthread_join(t2,NULL);
return 0;
}