/
moshroom_edu
/
evolution
Обзор
Документация
Войти
/
moshroom_edu
/
evolution
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
include/multithreading/queue.h
125 строк
2 KB
mushroom
resurrection
21 май 2026, 17:18
21 май 2026, 17:18
4d88a97
Код
Авторство
О чём код?
#ifndef QUEUE_H #define QUEUE_H #include <queue> #include <memory> #include <mutex> #include <condition_variable> #include <limits> namespace multithreading { template <class T> class queue { std::queue<std::shared_ptr<T>> m_data_q; mutable std::mutex m_mutex; std::condition_variable m_cond_var; size_t m_max_size; public: queue() : m_max_size(std::numeric_limits<size_t>().max()) { } bool push(T && val) { auto temp = std::make_shared<T>(std::move(val)); std::unique_lock<std::mutex> ulk(m_mutex); if(m_data_q.size() >= m_max_size) { return false; } m_data_q.push(temp); m_cond_var.notify_one(); return true; } bool push(const T & val) { auto temp = std::make_shared<T>(val); std::unique_lock<std::mutex> ulk(m_mutex); if(m_data_q.size() >= m_max_size) { return false; } m_data_q.push(temp); m_cond_var.notify_one(); return true; } std::shared_ptr<T> pop() { std::unique_lock<std::mutex> ulk(m_mutex); auto temp = m_data_q.front(); m_data_q.pop(); return temp; } size_t size() const { std::unique_lock<std::mutex> ulk(m_mutex); return m_data_q.size(); } bool try_pop(T & out) { std::unique_lock<std::mutex> ulk(m_mutex); if(!m_data_q.size()) { return false; } out = *m_data_q.front(); m_data_q.pop(); return true; } std::shared_ptr<T> wait_pop() { std::unique_lock<std::mutex> ulk(m_mutex); m_cond_var.wait(ulk, [this](){return m_data_q.size();}); auto temp = m_data_q.front(); m_data_q.pop(); return temp; } void wait_pop(T&val) { std::unique_lock<std::mutex> ulk(m_mutex); m_cond_var.wait(ulk, [this](){return m_data_q.size();}); val = *m_data_q.front(); m_data_q.pop(); } void clear() { std::unique_lock<std::mutex> ulk(m_mutex); m_data_q = std::move(std::queue<std::shared_ptr<T>>()); } void set_max_size(size_t _max_size) { std::unique_lock<std::mutex> ulk(m_mutex); m_max_size = _max_size; } size_t max_size() const { return m_max_size; } }; } //namespace multithreading #endif // QUEUE_H