#include <semaphore.h>
#include <fcntl.h>
#include <iostream>
#include <vector>
#include <unistd.h>
using namespace std;
sem_t semProducer,semConsumer;
vector<int> v;
void* producer(void*)
{
while(1)
{
if(v.size()>=5)
{
sem_post(&semConsumer);
sem_wait(&semProducer);
}else
{
v.push_back(1);
cout << "push,size:" << v.size() << endl;
sleep(1);
}
}
pthread_detach(pthread_self());
return 0;
}
void* consumer(void*)
{
while(1)
{
if(v.empty())
{
sem_post(&semProducer);
sem_wait(&semConsumer);
}else
{
v.pop_back();
cout << "pop,size:" << v.size() << endl;
sleep(1);
}
}
pthread_detach(pthread_self());
return 0;
}
int main()
{
sem_init(&semProducer,0,0);
sem_init(&semConsumer,0,1);
pthread_t pidProducer,pidConsumer;
pthread_create(&pidProducer,NULL,producer,NULL);
pthread_create(&pidConsumer,NULL,consumer,NULL);
sleep(10);
cout << "destroy ret:" << sem_destroy(&semConsumer) << endl;
cout << "destroy ret:" << sem_destroy(&semProducer) << endl;
}
push,size:1
push,size:2
push,size:3
push,size:4
push,size:5
pop,size:4
pop,size:3
pop,size:2
pop,size:1
pop,size:0
destroy ret:0
destroy ret:0
等待超时终止
#include <semaphore.h>
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
using namespace std;
sem_t sem;
void* testWait(void*)
{
while(1)
{
sleep(10);
sem_post(&sem);
cout << "post sem" << endl;
}
pthread_detach(pthread_self());
return 0;
}
int main()
{
sem_init(&sem,0,0);
pthread_t pidWait;
pthread_create(&pidWait,NULL,testWait,NULL);
struct timespec timeEnd;
struct timeval timeNow;
gettimeofday(&timeNow,NULL);
timeEnd.tv_sec = timeNow.tv_sec+5;
sem_timedwait(&sem,&timeEnd);
cout << "wait finished" << endl;
sleep(10);
cout << "destroy ret:" << sem_destroy(&sem) << endl;
}
wait finished
post sem
destroy ret:0