Skip to content

Commit 7f74d89

Browse files
aentingerfacchinm
authored andcommitted
Using rtos::MemoryPool to store the queued data elements rather than handling the heap memory management oneself
1 parent 08e5a56 commit 7f74d89

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

Arduino_Threads.h

+19-6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
#include <MemoryPool.h>
2+
3+
14
template<class T>
25
class Shared // template definition
36
{
@@ -7,9 +10,14 @@ class Shared // template definition
710
operator T() {
811
osEvent evt = queue.get();
912
if (evt.status == osEventMessage) {
10-
T x = *((T*)evt.value.p);
11-
delete (T*)evt.value.p;
12-
return x;
13+
/* Obtain the oldest inserted element from the queue. */
14+
T * val_ptr = reinterpret_cast<T *>(evt.value.p);
15+
/* Copy the content of T stored in the memory pool since we'll have to free the memory pool afterwards. */
16+
T const tmp_val = *val_ptr;
17+
/* Free the allocated memory in the memory pool. */
18+
memory_pool.free(val_ptr);
19+
/* Return obtained value from queue. */
20+
return tmp_val;
1321
}
1422
return val;
1523
}
@@ -19,9 +27,13 @@ class Shared // template definition
1927
T discard = *this;
2028
}
2129
val = other;
22-
T* obj = new T(val);
23-
queue.put(obj);
24-
return (*obj);
30+
/* Allocate memory in the memory pool. */
31+
T * val_ptr = memory_pool.alloc();
32+
/* Copy the content of 'other' into the freshly allocated message. */
33+
*val_ptr = other;
34+
/* Insert into queue. */
35+
queue.put(val_ptr);
36+
return (*val_ptr);
2537
}
2638
T& peek() {
2739
return val;
@@ -31,6 +43,7 @@ class Shared // template definition
3143
}
3244
private:
3345
T val;
46+
rtos::MemoryPool<T, 16> memory_pool;
3447
rtos::Queue<T, 16> queue;
3548
};
3649

0 commit comments

Comments
 (0)