/
AirLexa
/
06
Обзор
Документация
Войти
/
AirLexa
/
06
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lesson_06/SafeQueue/safe_queue.h
74 строки
2 KB
AirLexa
курсовая
19 июн 2026, 14:48
Верифицирован
19 июн 2026, 14:48
d9b94c2
Код
Авторство
О чём код?
#pragma once #include <queue> #include <mutex> #include <condition_variable> #include <functional> #include <optional> #include <atomic> template <typename T> class safe_queue { public: safe_queue() = default; ~safe_queue() = default; safe_queue(const safe_queue&) = delete; safe_queue& operator=(const safe_queue&) = delete; // Помещает новую задачу в очередь и уведомляет один из ожидающих потоков void push(T value) { std::lock_guard<std::mutex> lock(mutex_); queue_.push(std::move(value)); cond_var_.notify_one(); } // Извлекает задачу из очереди. Блокируется, пока очередь пуста, либо пока не будет вызвана shutdown() bool pop(T& value) { std::unique_lock<std::mutex> lock(mutex_); cond_var_.wait(lock, [this] { return !queue_.empty() || stopped; }); if (queue_.empty()) { // Очередь пуста и при этом был вызван shutdown return false; } value = std::move(queue_.front()); queue_.pop(); return true; } bool empty() const { std::lock_guard<std::mutex> lock(mutex_); return queue_.empty(); } size_t size() const { std::lock_guard<std::mutex> lock(mutex_); return queue_.size(); } // Останавливает очередь и пробуждает все ожидающие потоки void shutdown() { std::lock_guard<std::mutex> lock(mutex_); stopped = true; cond_var_.notify_all(); } private: std::queue<T> queue_; mutable std::mutex mutex_; std::condition_variable cond_var_; bool stopped = false; };