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

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

     
     
  • 相关阅读:
    tcpdump 筛选抓包
    TCP拥塞避免
    【转载】TCP协议
    go 参数传递的是值还是引用 (转)
    go 数组指针 指针数组
    go 协程
    go 接口实现
    go函数可见性
    go 继承
    go 结构体函数
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4831056.html
Copyright © 2011-2022 走看看