• 线程安全的队列


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

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

     
     
  • 相关阅读:
    git常用命令
    git误删文件找回方法/git版本回退方法
    如何解决inline和linline-block在浏览器中的间距问题
    windows系统如何添加ssh key到github
    如何使用git命令添加文件和提交文件
    sublime text常用快捷键
    sublime text3好用的插件
    Atom编辑器的插件
    使用SharedPreference保存用户数据的步骤
    解析xml文件步骤 -- pullparser
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4831056.html
Copyright © 2020-2023  润新知