ESPHome 2026.8.0
Loading...
Searching...
No Matches
lock_free_queue.h
Go to the documentation of this file.
1#pragma once
2
4
5#include <atomic>
6#include <cstddef>
7
8#ifdef USE_ESP32
9#include <freertos/FreeRTOS.h>
10#include <freertos/task.h>
11#endif
12
13/*
14 * Lock-free queue for single-producer single-consumer scenarios.
15 * This allows one thread to push items and another to pop them without
16 * blocking each other.
17 *
18 * This is a Single-Producer Single-Consumer (SPSC) lock-free ring buffer.
19 * Available on multi-threaded platforms (ESP32, LibreTiny) where another task
20 * produces or consumes, and on single-threaded platforms (RP2) where the
21 * producer runs in interrupt context.
22 *
23 * Common use cases:
24 * - BLE events: BLE task produces, main loop consumes
25 * - MQTT messages: main task produces, MQTT thread consumes
26 *
27 * @tparam T The type of elements stored in the queue (must be a pointer type)
28 * @tparam SIZE The maximum number of elements (1-255, limited by uint8_t indices)
29 */
30
31namespace esphome {
32
33namespace lockfree_internal {
34#if defined(ESPHOME_THREAD_MULTI_NO_ATOMICS) || defined(ESPHOME_THREAD_SINGLE)
35// Platforms where std::atomic RMW operations are unavailable or unnecessary:
36// - ESPHOME_THREAD_MULTI_NO_ATOMICS: cores lacking atomic read-modify-write
37// instructions (currently the ARMv5TE BK72xx SoCs — no LDREX/STREX, no
38// libatomic; other LibreTiny chips such as LN882x/RTL87xx are ARMv7-M and
39// keep std::atomic).
40// - ESPHOME_THREAD_SINGLE: every platform on this model (ESP8266, RP2,
41// nRF52) runs everything on one core (the chip may have more — RP2 is
42// dual-core, but ESPHome and its interrupt producers stay on core 0), so
43// the only possible concurrency is same-core interrupt preemption (on RP2
44// the BTstack packet handler runs in the CYW43 async-context low-priority
45// IRQ on the core that initialized it, core 0). Using plain accesses here
46// also avoids __atomic_* library calls on RP2040 (Cortex-M0+, no
47// LDREX/STREX).
48// For this queue's SPSC contract RMW atomics are not needed: aligned 8/16-bit
49// loads and stores are single instructions on these cores, so torn reads
50// cannot occur, and on a single in-order core a compiler barrier supplies all
51// the acquire/release ordering the algorithm requires. Each index has exactly
52// one writer (head_: consumer, tail_: producer). The dropped counter's
53// increment/exchange pair is not atomic here — a concurrent reset can lose
54// counts — which is acceptable for a diagnostic drop counter.
55#define ESPHOME_LFQ_COMPILER_BARRIER() __asm__ __volatile__("" ::: "memory")
56template<typename T> class PlainAtomic {
57 public:
58 PlainAtomic() = default;
59 constexpr PlainAtomic(T value) : value_(value) {}
60 T load(std::memory_order order = std::memory_order_seq_cst) const {
61 T value = value_;
62 if (order != std::memory_order_relaxed)
63 ESPHOME_LFQ_COMPILER_BARRIER(); // acquire: later reads may not hoist above this load
64 return value;
65 }
66 void store(T value, std::memory_order order = std::memory_order_seq_cst) {
67 if (order != std::memory_order_relaxed)
68 ESPHOME_LFQ_COMPILER_BARRIER(); // release: earlier writes may not sink below this store
69 value_ = value;
70 }
71 T fetch_add(T amount, std::memory_order /*order*/ = std::memory_order_seq_cst) {
72 T value = value_;
73 value_ = value + amount;
74 return value;
75 }
76 T exchange(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) {
77 T value = value_;
78 value_ = desired;
79 return value;
80 }
81
82 private:
83 volatile T value_{0};
84};
85template<typename T> using AtomicIndex = PlainAtomic<T>;
86#else
87template<typename T> using AtomicIndex = std::atomic<T>;
88#endif
89} // namespace lockfree_internal
90
91// Base lock-free queue without task notification
92template<class T, uint8_t SIZE> class LockFreeQueue {
93 public:
95
96 bool push(T *element) {
97 bool was_empty;
98 uint8_t old_tail;
99 return push_internal_(element, was_empty, old_tail);
100 }
101
102 protected:
103 // Advance ring buffer index by one, wrapping at SIZE.
104 // Power-of-2 sizes use modulo (compiler emits single mask instruction).
105 // Non-power-of-2 sizes use comparison to avoid expensive multiply-shift sequences.
106 static constexpr uint8_t next_index(uint8_t index) {
107 if constexpr ((SIZE & (SIZE - 1)) == 0) {
108 return (index + 1) % SIZE;
109 } else {
110 uint8_t next = index + 1;
111 if (next >= SIZE) [[unlikely]]
112 next = 0;
113 return next;
114 }
115 }
116
117 // Internal push that reports queue state - for use by derived classes
118 bool push_internal_(T *element, bool &was_empty, uint8_t &old_tail) {
119 if (element == nullptr)
120 return false;
121
122 uint8_t current_tail = tail_.load(std::memory_order_relaxed);
123 uint8_t next_tail = next_index(current_tail);
124
125 // Read head before incrementing tail
126 uint8_t head_before = head_.load(std::memory_order_acquire);
127
128 if (next_tail == head_before) {
129 // Buffer full
130 dropped_count_.fetch_add(1, std::memory_order_relaxed);
131 return false;
132 }
133
134 was_empty = (current_tail == head_before);
135 old_tail = current_tail;
136
137 buffer_[current_tail] = element;
138 tail_.store(next_tail, std::memory_order_release);
139
140 return true;
141 }
142
143 public:
144 T *pop() {
145 uint8_t current_head = head_.load(std::memory_order_relaxed);
146
147 if (current_head == tail_.load(std::memory_order_acquire)) {
148 return nullptr; // Empty
149 }
150
151 T *element = buffer_[current_head];
152 head_.store(next_index(current_head), std::memory_order_release);
153 return element;
154 }
155
156 size_t size() const {
157 uint8_t tail = tail_.load(std::memory_order_acquire);
158 uint8_t head = head_.load(std::memory_order_acquire);
159 if constexpr ((SIZE & (SIZE - 1)) == 0) {
160 return (tail - head + SIZE) % SIZE;
161 } else {
162 int diff = static_cast<int>(tail) - static_cast<int>(head);
163 if (diff < 0)
164 diff += SIZE;
165 return static_cast<size_t>(diff);
166 }
167 }
168
170 // Fast path: relaxed load is a single instruction on all platforms.
171 // The atomic exchange (especially for uint16_t on Xtensa) compiles to
172 // an expensive sub-word CAS retry loop (~25 instructions + memory barriers).
173 // Since drops are rare, avoid the exchange in the common case.
174 if (dropped_count_.load(std::memory_order_relaxed) == 0)
175 return 0;
176 return dropped_count_.exchange(0, std::memory_order_relaxed);
177 }
178
179 void increment_dropped_count() { dropped_count_.fetch_add(1, std::memory_order_relaxed); }
180
181 bool empty() const { return head_.load(std::memory_order_acquire) == tail_.load(std::memory_order_acquire); }
182
183 bool full() const {
184 uint8_t next_tail = next_index(tail_.load(std::memory_order_relaxed));
185 return next_tail == head_.load(std::memory_order_acquire);
186 }
187
188 protected:
189 T *buffer_[SIZE]{};
190 // Atomic: written by producer (push/increment), read+reset by consumer (get_and_reset)
191 lockfree_internal::AtomicIndex<uint16_t> dropped_count_; // 65535 max - more than enough for drop tracking
192 // Atomic: written by consumer (pop), read by producer (push) to check if full
193 // Using uint8_t limits queue size to 255 elements but saves memory and ensures
194 // atomic operations are efficient on all platforms
196 // Atomic: written by producer (push), read by consumer (pop) to check if empty
198};
199
200#ifdef USE_ESP32
201// Extended queue with task notification support
202template<class T, uint8_t SIZE> class NotifyingLockFreeQueue : public LockFreeQueue<T, SIZE> {
203 public:
204 NotifyingLockFreeQueue() : LockFreeQueue<T, SIZE>(), task_to_notify_(nullptr) {}
205
206 bool push(T *element) {
207 bool was_empty;
208 uint8_t old_tail;
209 bool result = this->push_internal_(element, was_empty, old_tail);
210
211 // Notify optimization: only notify if we need to
212 if (result && task_to_notify_ != nullptr &&
213 (was_empty || this->head_.load(std::memory_order_acquire) == old_tail)) {
214 // Notify in two cases:
215 // 1. Queue was empty - consumer might be going to sleep
216 // 2. Consumer just caught up to where tail was - might go to sleep
217 // Note: There's a benign race in case 2 - between reading head and calling
218 // xTaskNotifyGive(), the consumer could advance further. This would result
219 // in an unnecessary wake-up, but is harmless and extremely rare in practice.
220 xTaskNotifyGive(task_to_notify_);
221 }
222 // Otherwise: consumer is still behind, no need to notify
223
224 return result;
225 }
226
227 // Set the FreeRTOS task handle to notify when items are pushed to the queue
228 // This enables efficient wake-up of a consumer task that's waiting for data
229 // @param task The FreeRTOS task handle to notify, or nullptr to disable notifications
230 void set_task_to_notify(TaskHandle_t task) { task_to_notify_ = task; }
231
232 private:
233 TaskHandle_t task_to_notify_;
234};
235#endif
236
237} // namespace esphome
uint16_t get_and_reset_dropped_count()
bool push(T *element)
static constexpr uint8_t next_index(uint8_t index)
lockfree_internal::AtomicIndex< uint8_t > head_
bool push_internal_(T *element, bool &was_empty, uint8_t &old_tail)
lockfree_internal::AtomicIndex< uint16_t > dropped_count_
lockfree_internal::AtomicIndex< uint8_t > tail_
void set_task_to_notify(TaskHandle_t task)
T fetch_add(T amount, std::memory_order=std::memory_order_seq_cst)
T exchange(T desired, std::memory_order=std::memory_order_seq_cst)
T load(std::memory_order order=std::memory_order_seq_cst) const
void store(T value, std::memory_order order=std::memory_order_seq_cst)