boost condition

来源:互联网 发布:php 查找网页内容 编辑:程序博客网 时间:2024/04/27 15:51
1.简介
condition是一个简单的同步对象,用于使一个线程等待一个特定的条件成立(比如
资源可用)。一个condition对象总是和一个mutex对象配合使用。mutex在交给condition
对象的wait系列函数时,必须已经通过lock对象加上了锁。当线程陷入等待时,condtion
对象将释放mutex上的锁,当wait返回时,mutex上的锁会重新加上,这一unlock/lock
动作由conditon对象自动完成。

2.使用
namespace boost
{
    class condition : private boost::noncopyable // Exposition only.
       // Class condition meets the NonCopyable requirement.
    {
    public:
        condition();
        ~condition();

        void notify_one();
//      唤起等待队列中的一个线程
        void notify_all();
//      唤起等待队列中的所有线程
        template <typename Lock> void wait(Lock& lock);
//      ScopedLock 是一个lock对象,符合ScopedLock 概念
//      释放lock中mutex上的锁,阻塞该线程,直到任何人调用了this->notify_one()或
//      this->notify_all(),然后重新lock mutex。
        template <typename Lock, typename Predicate>
            void void wait(Lock& lock, Predicate pred);
//      ScopedLock 是一个lock对象,符合ScopedLock 概念
//      相当于while (!pred()) wait(lock)。
        template <typename Lock>
            bool timed_wait(Lock& lock, const xtime& xt);
//      wait(Lock& lock)的限时版,当XT到达时,函数返回false,当因notify而返回时
//      函数返回true
        template <typename Lock, typename Predicate>
            bool timed_wait(Lock& lock, const xtime& XT, Predicate pred);

//      wait(Lock& lock, Predicate pred)的限时版,当XT到达时,函数返回false,当
//      因notify和pred而而返回时函数返回true
    };
};

3.例子
一个经典的消息队列的实现
#include <iostream>
#include <vector>
#include <boost/utility.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>

class bounded_buffer : private boost::noncopyable
{
public:
    typedef boost::mutex::scoped_lock lock;

    bounded_buffer(int n) : begin(0), end(0), buffered(0), circular_buf(n) { }

    void send (int m) { //      加入消息
        lock lk(monitor);
        while (buffered == circular_buf.size())
            buffer_not_full.wait(lk);
        circular_buf[end] = m;
        end = (end+1) % circular_buf.size();
        ++buffered;
        buffer_not_empty.notify_one();
    }
    int receive() {     //      取走消息
        lock lk(monitor);
        while (buffered == 0)
            buffer_not_empty.wait(lk);
        int i = circular_buf[begin];
        begin = (begin+1) % circular_buf.size();
        --buffered;
        buffer_not_full.notify_one();
        return i;
    }

private:
    int begin, end, buffered;
    std::vector<int> circular_buf;
    boost::condition buffer_not_full, buffer_not_empty;
    boost::mutex monitor;
};