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

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

     
     
  • 相关阅读:
    Layui数据表格用法
    初识Vue
    使用NPOI导出Excel表
    使用NPOI将Excel表导入到数据库中
    新随笔
    AX2012/D365 SSRS报表开发
    AX2012自定义注释脚本开发
    D365做文件导入导出CSV
    Azure文件上传下载删除(D365可以直接用)
    关于D365/AX2012/C#中的那些json、对象、字符串类型间的转换
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4831056.html
Copyright © 2011-2022 走看看