/
dmitriy.grischenkov
/
calcstc
Обзор
Документация
Войти
/
dmitriy.grischenkov
/
calcstc
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/threadsafequeue.h
62 строки
1 KB
Dmitriy Grischenkov
first load
01 авг 2026, 21:35
01 авг 2026, 21:35
166b1b5
Код
Авторство
О чём код?
#pragma once #include <thread> #include <mutex> #include <atomic> #include <condition_variable> #include <queue> template <typename T> class ThreadSafeQueue { public: void push(const T& v) { { std::lock_guard<std::mutex> lock(m_mutex); m_queue.push(v); } m_cond.notify_one(); } bool pop(T& out) { std::unique_lock<std::mutex> lock(m_mutex); while (m_queue.empty() && !m_stop) { m_cond.wait(lock); } if (m_queue.empty()) { return false; } out = std::move(m_queue.front()); m_queue.pop(); return true; } bool tryPop(T& out) { std::lock_guard<std::mutex> lock(m_mutex); if (m_queue.empty()) { return false; } out = std::move(m_queue.front()); m_queue.pop(); return true; } std::size_t size() const { std::lock_guard<std::mutex> lock(m_mutex); return m_queue.size(); } void shutdown() { { std::lock_guard<std::mutex> lock(m_mutex); m_stop = true; } m_cond.notify_all(); } private: std::queue<T> m_queue; mutable std::mutex m_mutex; std::condition_variable m_cond; std::atomic<bool> m_stop{false}; };