SlideIO 2.0.0
Open-source library for reading of medical images
Loading...
Searching...
No Matches
boundedqueue.hpp
1// This file is part of slideio project.
2// It is subject to the license terms in the LICENSE file found in the top-level directory
3// of this distribution and at http://slideio.com/license.html.
4//
5#pragma once
6#include <thread>
7#include <queue>
8#include <mutex>
9#include <condition_variable>
10#include <vector>
11#include <functional>
12#include <optional>
13#include <map>
14
15// --- Thread-safe bounded queue ---
16template<typename T>
17class BoundedQueue {
18public:
19 explicit BoundedQueue(size_t maxSize) : maxSize_(maxSize) {}
20
21 bool push(T item) {
22 std::unique_lock lock(mutex_);
23 cvNotFull_.wait(lock, [&] { return queue_.size() < maxSize_ || done_; });
24 if (done_)
25 return false; // Queue is shutting down, discard item
26 queue_.push(std::move(item));
27 cvNotEmpty_.notify_one();
28 return true;
29 }
30 std::optional<T> pop() {
31 std::unique_lock lock(mutex_);
32 cvNotEmpty_.wait(lock, [&]{ return !queue_.empty() || done_; });
33 if (queue_.empty())
34 return std::nullopt; // Signals shutdown
35 T item = std::move(queue_.front());
36 queue_.pop();
37 cvNotFull_.notify_one();
38 return item;
39 }
40
41 void setDone() {
42 std::unique_lock lock(mutex_);
43 done_ = true;
44 cvNotEmpty_.notify_all();
45 cvNotFull_.notify_all();
46 }
47
48private:
49 std::queue<T> queue_;
50 std::mutex mutex_;
51 std::condition_variable cvNotEmpty_;
52 std::condition_variable cvNotFull_;
53 size_t maxSize_;
54 bool done_ = false;
55};