返回顶部

收藏

C++ 消息队列

更多
#include <deque>

#pragma warning(disable:4251)
#pragma warning(disable:4275)
#include <boost/assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#pragma warning(default:4275)
#pragma warning(default:4251)

template<class T>
class EWQueue
    : public boost::noncopyable
{
public:
    EWQueue();
    virtual ~EWQueue();

    void put(T obj);
    T get();
    void wait();
    bool empty();

private:
    typedef std::deque<T> Collection_t;

    Collection_t m_queue;
    boost::mutex m_queuemutex;

    boost::condition m_nonemptycondition;
};

template<class T>
EWQueue<T>::EWQueue()
{
}

template<class T>
EWQueue<T>::~EWQueue()
{
}

template<class T>
void EWQueue<T>::put(T obj)
{
    boost::mutex::scoped_lock lock(m_queuemutex);
    m_queue.push_back(obj);

    m_nonemptycondition.notify_one();
}

template<class T>
T EWQueue<T>::get()
{
    boost::mutex::scoped_lock lock(m_queuemutex);
    BOOST_ASSERT(!m_queue.empty());
    T retval(m_queue.front());
    m_queue.pop_front();
    return(retval);
}

template<class T>
void EWQueue<T>::wait()
{
    boost::mutex::scoped_lock lock(m_queuemutex);

    if (!m_queue.empty())
        return;

    m_nonemptycondition.wait(lock);
}

template<class T>
bool EWQueue<T>::empty()
{
    boost::mutex::scoped_lock lock(m_queuemutex);
    return(m_queue.empty());
}

标签:C++,消息队列

收藏

0人收藏

支持

0

反对

0

发表评论