有锁的线程安全栈

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()
    {
        std::lock_guard<std::mutex> lock(m);
        if (data.empty()){
            return std::shared_ptr<T>();
        }
        auto const result = std::make_shared<T>(std::move(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();
    }
    
};
原文地址:https://www.cnblogs.com/wuOverflow/p/4885198.html