码迷,mamicode.com
首页 > 编程语言 > 详细

有锁的线程安全栈

时间:2015-10-16 15:09:29      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:

template<typename T>
class ThreadSafeStack
{
private:
    std::stack<T>      data;
    mutable std::mutex m;
public:
    ThreadSafeStack() = default;
    ThreadSafeStack(const ThreadSafeStack& other)
    {
        std::lock_guard<std::mutex> lock(other.m);
        data = other.data;
    }
    ThreadSafeStack& operator=(const ThreadSafeStack&) = delete;
    
    void push(T newValue)
    {
        std::lock_guard<std::mutex> lock(m);
        data.push(std::move(newValue));
    }
    
    std::shared_ptr<T> pop()
    {
        if (data.empty()){
            return std::shared_ptr<T>();
        }
        auto const result = std::make_shared<T>(data.top());
        data.pop();
        return result;
    }
    
    void pop(T& popedValue)
    {
        std::lock_guard<std::mutex> lock(m);
        if (data.empty()){
            return;
        }
        
        popedValue = std::move(data.top());
        data.pop();
    }
    
    bool empty()
    {
        std::lock_guard<std::mutex> lock(m);
        return data.empty();
    }
    
};

 

有锁的线程安全栈

标签:

原文地址:http://www.cnblogs.com/wuOverflow/p/4885198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!