线程安全的队列

template<typename T>
class ThreadsafeQueue
{
private:
    mutable std::mutex              _mut;
    std::queue<std::shared_ptr<T>>  _dataQueue;
    std::condition_variable         _dataCond;
public:
    ThreadsafeQueue() = default;
    void push(T newValue)
    {
        std::lock_guard<std::mutex> lock(_mut);
        _dataQueue.push (std::make_shared<T>(std::move(newValue)));
        _dataCond.notify_one ();
    }

    void waitAndPop (T &value)
    {
        std::unique_lock<std::mutex> lock(_mut);
        _dataCond.wait (lock, [this]{return !_dataQueue.empty ();});
        value = std::move(*_dataQueue.front ());
        _dataQueue.pop ();
    }

    std::shared_ptr<T> waitAndPop ()
    {
        std::unique_lock<std::mutex> lock(_mut);
        _dataCond.wait(lock, [this]{return !_dataQueue.empty ();});
        auto pPopedValue = std::move(_dataQueue.front ());
        _dataQueue.pop ();
        return pPopedValue;
    }

    bool tryPop (T &value)
    {
        std::lock_guard<std::mutex> lock(_mut);
        if (_dataQueue.empty ()){
            return false;
        }
        value = std::move(*_dataQueue.front ());
        _dataQueue.pop ();
        return true;
    }

    std::shared_ptr<T> tryPop ()
    {
        std::lock_guard<std::mutex> lock(_mut);
        if (_dataQueue.empty ()){
            return std::make_shared<T>();
        }
        auto result = std::move(_dataQueue.front ());
        _dataQueue.pop ();
        return result;
    }

    bool empty () const
    {
        std::lock_guard<std::mutex> lock(_mut);
        return _dataQueue.empty ();
    }
};

 这样确实可以实现并发,但是效率极低,因为一次只能有一个线程可以操作,无法发挥并发的真正优势。

 
 
posted @ 2015-09-23 01:21  wu_overflow  阅读(265)  评论(0编辑  收藏  举报