Loading...
Searching...
No Matches
thread_safe_queue.h
Go to the documentation of this file.
1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 Artificial Intelligence Techniques, S.L. and Roberto López González
3
4#pragma once
5
6#include <condition_variable>
7#include <mutex>
8#include <queue>
9#include <utility>
10
11namespace opennn
12{
13
14template <typename T>
16{
17public:
18
19 void push(T item)
20 {
21 { std::lock_guard<std::mutex> lock(mutex_); queue_.push(std::move(item)); }
22 cond_.notify_one();
23 }
24
25 bool wait_pop(T& item)
26 {
27 std::unique_lock<std::mutex> lock(mutex_);
28 cond_.wait(lock, [this] { return !queue_.empty() || closed_; });
29 if (queue_.empty()) return false;
30
31 item = std::move(queue_.front());
32 queue_.pop();
33 return true;
34 }
35
36 void close()
37 {
38 { std::lock_guard<std::mutex> lock(mutex_); closed_ = true; }
39 cond_.notify_all();
40 }
41
42 void reopen()
43 {
44 std::lock_guard<std::mutex> lock(mutex_);
45 closed_ = false;
46 }
47
48private:
49
50 std::queue<T> queue_;
51 std::mutex mutex_;
52 std::condition_variable cond_;
53 bool closed_ = false;
54};
55
56}
Definition thread_safe_queue.h:16
void reopen()
Definition thread_safe_queue.h:42
void push(T item)
Definition thread_safe_queue.h:19
bool wait_pop(T &item)
Definition thread_safe_queue.h:25
void close()
Definition thread_safe_queue.h:36
Definition configuration.h:10