class condition:noncopyable
{
};
实现了最简单condtion操作,包括init,destroy,wait,notify,notifyAll,waitforseconds操作,
内部数据也很简单,mutexlock& m_mutex和pthread_cond_t m_cond
使用方法和std::cond一样
private:
mutexlock& m_mutex;
pthread_cond_t m_cond;
public:
explicit condition(mutexlock& mutex):m_mutex(mutex)
{
pthread_cond_init(&m_cond,NULL);
}
~condition()
{
pthread_cond_destroy(&m_cond);
}
//不满足条件时wait,把mutexlock中m_holder移除,同时该线程释放该锁
void wait()
{
mutexlock::UnassignGuard ug(m_mutex);
pthread_cond_wait(&m_cond,m_mutex.getPthreadMutex());
}
//等待一段时间而不是一直等待
bool waitForSeconds(double seconds);
//唤醒cond阻塞队列中的第一个线程
void notify()
{
pthread\_cond\_signal(&m\_cond);
}
//唤醒cond阻塞队列中的所有线程
void notifyAll()
{
pthread\_cond\_broadcast(&m\_cond);
}
使用condtion和mutex完成一个生产者消费者同步的小例子。
#include"base/mutex.h"
#include"base/condition.h"
#include
#include
#include
#include
#define MAXQUEUE 5
mymuduo::mutexlock mutex;
mymuduo::condition cond(mutex);
std::queue
namespace mymuduo{
namespace currentthread {
void cacheTid()
{
}
}
}
void provider()
{
while()
{
std::this_thread::sleep_for(std::chrono::milliseconds());
mymuduo::mutexlockguard mlg(mutex);
while(task_queue.size()>=MAXQUEUE)
cond.wait();
task_queue.push(rand()%);
std::cout<<"push "<<task_queue.front()<<std::endl;
cond.notifyAll();
}
}
void consumer()
{
while()
{
mymuduo::mutexlockguard mlg(mutex);
while(task_queue.empty())
cond.wait();
std::cout<<"pop "<<task_queue.front()<<std::endl;
task_queue.pop();
cond.notifyAll();
}
}
int main()
{
std::thread t[];
t[]=std::thread(provider);
t[]=std::thread(consumer);
t[].join();t[].join();
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章