#ifndef __POOL_H__ #define __POOL_H__ #include #include #include template class Pool { public: Pool() : _head(nullptr) {} Pool(const Pool &) = delete; Pool(Pool &&pool) noexcept : _head(pool._head.exchange(nullptr)) {} ~Pool() { while (this->pop()) {} } void push(T &&val) const { Node *new_node = new Node(std::move(val)); new_node->next = _head.load(); while (!_head.compare_exchange_weak(new_node->next, new_node)); } std::optional pop() const { Node *top = _head.load(); Node *new_head = nullptr; do { if (!top) { return std::nullopt; } new_head = top->next; } while (!_head.compare_exchange_weak(top, new_head)); return {std::move(top->data)}; } private: template struct Node { U data; Node *next; Node(U &&data) : data(data), next(nullptr) {} }; mutable std::atomic *> _head; }; #endif // __POOL_H__