#ifndef stack_h #define stack_h 1 #include #include #include #include using namespace std::chrono_literals; class semaphore : public std::binary_semaphore { public: semaphore() : std::binary_semaphore(1) {} void lock() { auto delay = 50us; while (!try_acquire()) std::this_thread::sleep_for(delay *= 2); } void unlock() { release(); } }; template class stack { public: void push(T t) { std::scoped_lock lock(sem); container.push(t); } std::optional pop() { std::scoped_lock lock(sem); if (!container.empty()) { auto data = container.top(); container.pop(); return data; } else { return std::nullopt; } } private: semaphore sem; std::stack container; }; #endif // stack_h