Muduo里的blockingQueue实现线程池伪码

来源:互联网 发布:centos mv 移动文件夹 编辑:程序博客网 时间:2024/06/05 23:45
#include <muduo/base/Condition.h>#include <muduo/base/Mutex.h>#include <boost/noncopyable.hpp>#include <deque>#include <assert.h>template<typename T>class BlockingQueue : boost::noncopyable{ public:    BlockingQueue(): mutex_(),notEmpty_(mutex_),queue_(){}    void put(const T& x)    {        MutexLockGuard lock(mutex_);//安全加锁pthread_mutex_t        queue_.push_back(x);        notEmpty_.notify(); // wait morphing saves us        // http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/    }    T take()    {        MutexLockGuard lock(mutex_);        // always use a while-loop, due to spurious wakeup        while (queue_.empty())        {            notEmpty_.wait();        }        assert(!queue_.empty());        T front(queue_.front());        queue_.pop_front();        return front;    }    size_t size() const    {        MutexLockGuard lock(mutex_);        return queue_.size();    } private:    mutable MutexLock mutex_;//pthread_mutex_t的封装    Condition         notEmpty_;//pthread_cond_t的封装    std::deque<T>     queue_;};//用阻塞对咧咧实现任务队列typedef boost::function<void()> Functor;BlockingQueue<Functor> taskQueue;//线程安全的阻塞队列void workThread(){    while(running){        Functor task=taskQueue.take();        task();//考虑异常处理    }}int N=num_of_computing_threads;for(int i=0;i<N;i++){    create_thread(&workThread);//启动线程}Foo foo;boost::function<void()> task=boost::bind(&Foo::calc,&foo);taskQueue.post(task);

原创粉丝点击