zoukankan      html  css  js  c++  java
  • 线程安全的队列

    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 ();
        }
    };

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

     
     
  • 相关阅读:
    selenium产生的垃圾文件清理
    英语学习词根法
    ecommerce学习
    tfs2012安装
    转载文件,英语学习
    Mishka and Divisors CodeForces
    Codeforces Round #364 (Div. 1) (差一个后缀自动机)
    莫比乌斯反演练习
    bzoj 1267 Kth Number I (点分治,堆)
    程序员的绘图利器 — Gnuplot
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4831056.html
Copyright © 2011-2022 走看看