Lamp-Da 0.1
A compact lantern project
Loading...
Searching...
No Matches
thread_safe_queue.h
Go to the documentation of this file.
1
5#ifndef UTILS_THREAD_SAFE_QUEUE_H
6#define UTILS_THREAD_SAFE_QUEUE_H
7
8#include <cstddef>
9
10#include <etl/optional.h>
11#include <etl/queue.h>
12
13#include "src/system/hal/mutex.h"
14
15namespace lampda {
16namespace utils {
17
23template<typename T, size_t N> class ThreadSafeQueue
24{
25public:
26 ThreadSafeQueue() { hal::mutex::hal_mutex_init(&_mutex); }
27
28 ThreadSafeQueue(const ThreadSafeQueue&) = delete;
29 ThreadSafeQueue& operator=(const ThreadSafeQueue&) = delete;
30
35 bool push(const T& item)
36 {
37 Lock lock(_mutex);
38 // pushing in a full etl::queue is an assert
39 if (_queue.full())
40 return false;
41 _queue.push(item);
42 return true;
43 }
44
49 etl::optional<T> pop()
50 {
51 Lock lock(_mutex);
52 if (_queue.empty())
53 return etl::nullopt;
54 etl::optional<T> item(_queue.front());
55 _queue.pop();
56 return item;
57 }
58
60 size_t size()
61 {
62 Lock lock(_mutex);
63 return _queue.size();
64 }
65
67 void clear()
68 {
69 Lock lock(_mutex);
70 _queue.clear();
71 }
72
74 static constexpr size_t capacity() { return N; }
75
76private:
78 struct Lock
79 {
80 explicit Lock(hal::mutex::hal_mutex_t& m) : _m(m) { hal::mutex::hal_mutex_lock(&_m); }
81 ~Lock() { hal::mutex::hal_mutex_unlock(&_m); }
82 Lock(const Lock&) = delete;
83 Lock& operator=(const Lock&) = delete;
84
85 private:
86 hal::mutex::hal_mutex_t& _m;
87 };
88
89 etl::queue<T, N> _queue;
90 hal::mutex::hal_mutex_t _mutex;
91};
92
93} // namespace utils
94} // namespace lampda
95
96#endif
Fixed capacity FIFO queue, guarded by a mutex. Push and pop can be called from any thread,...
Definition: thread_safe_queue.h:24
static constexpr size_t capacity()
Maximum number of stored items.
Definition: thread_safe_queue.h:74
bool push(const T &item)
Push an item at the end of the queue.
Definition: thread_safe_queue.h:35
void clear()
Drop all stored items.
Definition: thread_safe_queue.h:67
size_t size()
Return the number of stored items.
Definition: thread_safe_queue.h:60
etl::optional< T > pop()
Pop the oldest item.
Definition: thread_safe_queue.h:49
Program scope.
Definition: control_fixed_modes.hpp:14
Definition: mutex.h:49