ESPHome 2025.7.1
Loading...
Searching...
No Matches
event_pool.h
Go to the documentation of this file.
1#pragma once
2
3#if defined(USE_ESP32) || defined(USE_LIBRETINY)
4
5#include <atomic>
6#include <cstddef>
9
10namespace esphome {
11
12// Event Pool - On-demand pool of objects to avoid heap fragmentation
13// Events are allocated on first use and reused thereafter, growing to peak usage
14// @tparam T The type of objects managed by the pool (must have a release() method)
15// @tparam SIZE The maximum number of objects in the pool (1-255, limited by uint8_t)
16template<class T, uint8_t SIZE> class EventPool {
17 public:
18 EventPool() : total_created_(0) {}
19
21 // Clean up any remaining events in the free list
22 // IMPORTANT: This destructor assumes no concurrent access. The EventPool must not
23 // be destroyed while any thread might still call allocate() or release().
24 // In practice, this is typically ensured by destroying the pool only during
25 // component shutdown when all producer/consumer threads have been stopped.
26 T *event;
28 while ((event = this->free_list_.pop()) != nullptr) {
29 // Call destructor
30 event->~T();
31 // Deallocate using RAMAllocator
32 allocator.deallocate(event, 1);
33 }
34 }
35
36 // Allocate an event from the pool
37 // Returns nullptr if pool is full
38 T *allocate() {
39 // Try to get from free list first
40 T *event = this->free_list_.pop();
41 if (event != nullptr)
42 return event;
43
44 // Need to create a new event
45 if (this->total_created_ >= SIZE) {
46 // Pool is at capacity
47 return nullptr;
48 }
49
50 // Use internal RAM for better performance
52 event = allocator.allocate(1);
53
54 if (event == nullptr) {
55 // Memory allocation failed
56 return nullptr;
57 }
58
59 // Placement new to construct the object
60 new (event) T();
61 this->total_created_++;
62 return event;
63 }
64
65 // Return an event to the pool for reuse
66 void release(T *event) {
67 if (event != nullptr) {
68 // Clean up the event's allocated memory
69 event->release();
70 this->free_list_.push(event);
71 }
72 }
73
74 private:
75 LockFreeQueue<T, SIZE> free_list_; // Free events ready for reuse
76 uint8_t total_created_; // Total events created (high water mark, max 255)
77};
78
79} // namespace esphome
80
81#endif // defined(USE_ESP32) || defined(USE_LIBRETINY)
void release(T *event)
Definition event_pool.h:66
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:761
void deallocate(T *p, size_t n)
Definition helpers.h:819
T * allocate(size_t n)
Definition helpers.h:781
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7