PIDUINO
Loading...
Searching...
No Matches
tsqueue.h
1/* Copyright © 2018-2025 Pascal JEAN, All rights reserved.
2 This file is part of the Piduino Library.
3
4 The Piduino Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 3 of the License, or (at your option) any later version.
8
9 The Piduino Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with the Piduino Library; if not, see <http://www.gnu.org/licenses/>.
16*/
17#pragma once
18#include <condition_variable>
19#include <mutex>
20#include <queue>
21
22// based on https://www.geeksforgeeks.org/dsa/implement-thread-safe-queue-in-c/
23
24namespace Piduino {
34 template <typename T>
35 class TSQueue {
36 private:
37 std::queue<T> m_queue; //< Underlying queue container.
38 mutable std::mutex m_mutex; //< Mutex for synchronizing access.
39 std::condition_variable m_cond; //< Condition variable for blocking/waking threads.
40
41 public:
49 void push (T item) {
50
51 // Acquire lock
52 std::unique_lock<std::mutex> lock (m_mutex);
53
54 // Add item
55 m_queue.push (item);
56
57 // Notify one thread that
58 // is waiting
59 m_cond.notify_one();
60 }
61
69 T pop() {
70
71 // acquire lock
72 std::unique_lock<std::mutex> lock (m_mutex);
73
74 // wait until queue is not empty
75 m_cond.wait (lock,
76 [this]() {
77 return !m_queue.empty();
78 });
79
80 // retrieve item
81 T item = m_queue.front();
82 m_queue.pop();
83
84 // return item
85 return item;
86 }
87
95 bool empty() const {
96
97 // acquire lock
98 std::lock_guard<std::mutex> lock (m_mutex);
99
100 // return if queue is empty
101 return m_queue.empty();
102 }
103
111 size_t size() const {
112
113 // acquire lock
114 std::lock_guard<std::mutex> lock (m_mutex);
115
116 // return the size of the queue
117 return m_queue.size();
118 }
119
125 void clear() {
126
127 // acquire lock
128 std::lock_guard<std::mutex> lock (m_mutex);
129
130 // clear the queue
131 m_queue = std::queue<T>();
132 }
133 };
134}
Thread-safe queue implementation.
Definition tsqueue.h:35
void clear()
Clears the queue.
Definition tsqueue.h:125
void push(T item)
Pushes an item into the queue.
Definition tsqueue.h:49
bool empty() const
Checks if the queue is empty.
Definition tsqueue.h:95
std::mutex m_mutex
Definition tsqueue.h:38
std::queue< T > m_queue
Definition tsqueue.h:37
T pop()
Pops an item from the queue.
Definition tsqueue.h:69
size_t size() const
Gets the size of the queue.
Definition tsqueue.h:111
std::condition_variable m_cond
Definition tsqueue.h:39
Global namespace for Piduino.
Definition board.h:28