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(); } };
时间: 2024-10-26 22:42:44