Lightweight
0.20260617.0
Loading...
Searching...
No Matches
ThreadSafeQueue.hpp
1
// SPDX-License-Identifier: Apache-2.0
2
3
#pragma once
4
5
#include "BlockingQueue.hpp"
6
7
#include <cstddef>
8
#include <utility>
9
10
namespace
Lightweight
11
{
12
13
/// Thread-safe queue with blocking wait semantics.
14
///
15
/// This queue allows multiple producer and consumer threads to safely enqueue
16
/// and dequeue items. Consumers block on WaitAndPop until an item is available
17
/// or the queue is marked as finished.
18
///
19
/// It is a thin facade over @c detail::BlockingQueue (the shared blocking-FIFO primitive), so the
20
/// locking/wait logic lives in exactly one place rather than being hand-rolled here.
21
///
22
/// @tparam T The type of items stored in the queue.
23
template
<
typename
T>
24
class
ThreadSafeQueue
25
{
26
public
:
27
/// Pushes an item onto the queue and notifies one waiting consumer.
28
///
29
/// @param item The item to push onto the queue.
30
void
Push
(T item)
31
{
32
_queue.Push(std::move(item));
33
}
34
35
/// Blocks until an item is available or the queue is finished.
36
///
37
/// This method will block the calling thread until either:
38
/// - An item becomes available in the queue, or
39
/// - The queue has been marked as finished and is empty.
40
///
41
/// @param item Output parameter to receive the popped item.
42
/// @return true if an item was successfully popped, false if the queue is finished and empty.
43
bool
WaitAndPop
(T& item)
44
{
45
return
_queue.WaitAndPop(item);
46
}
47
48
/// Signals that no more items will be added.
49
///
50
/// After this call, WaitAndPop will return false once the queue is empty.
51
/// All waiting consumers will be notified.
52
void
MarkFinished
()
53
{
54
_queue.MarkFinished();
55
}
56
57
/// Checks if the queue is empty.
58
///
59
/// @return true if the queue is currently empty.
60
[[nodiscard]]
bool
Empty
()
const
61
{
62
return
_queue.Empty();
63
}
64
65
/// Returns the current size of the queue.
66
///
67
/// @return The number of items currently in the queue.
68
[[nodiscard]]
size_t
Size
()
const
69
{
70
return
_queue.Size();
71
}
72
73
private
:
74
detail::BlockingQueue<T> _queue;
75
};
76
77
}
// namespace Lightweight
Lightweight::ThreadSafeQueue
Definition
ThreadSafeQueue.hpp:25
Lightweight::ThreadSafeQueue::WaitAndPop
bool WaitAndPop(T &item)
Definition
ThreadSafeQueue.hpp:43
Lightweight::ThreadSafeQueue::Push
void Push(T item)
Definition
ThreadSafeQueue.hpp:30
Lightweight::ThreadSafeQueue::Size
size_t Size() const
Definition
ThreadSafeQueue.hpp:68
Lightweight::ThreadSafeQueue::MarkFinished
void MarkFinished()
Definition
ThreadSafeQueue.hpp:52
Lightweight::ThreadSafeQueue::Empty
bool Empty() const
Definition
ThreadSafeQueue.hpp:60
Lightweight
ThreadSafeQueue.hpp
Generated by
1.9.8