diff --git a/Arduino_Threads.h b/Arduino_Threads.h index 9c2f230..38c8634 100644 --- a/Arduino_Threads.h +++ b/Arduino_Threads.h @@ -3,18 +3,25 @@ class Shared // template definition { public: Shared() { - queue = new rtos::Queue, 16>; } - operator T() const { - osEvent evt = queue->get(); + operator T() { + osEvent evt = queue.get(); if (evt.status == osEventMessage) { - Shared *x = (Shared*)evt.value.p; - return x->val; + T x = *((T*)evt.value.p); + delete (T*)evt.value.p; + return x; } + return val; } T& operator= (const T& other) { + if (queue.full()) { + // invokes operator T() to discard oldest element and free its memory + T discard = *this; + } val = other; - queue->put(this); + T* obj = new T(val); + queue.put(obj); + return (*obj); } T& peek() { return val; @@ -24,7 +31,7 @@ class Shared // template definition } private: T val; - rtos::Queue, 16> *queue; + rtos::Queue queue; }; #define CONCAT2(x,y) x##y diff --git a/examples/Enqueue_test/Enqueue.inot b/examples/Enqueue_test/Enqueue.inot new file mode 100644 index 0000000..f7cfaf4 --- /dev/null +++ b/examples/Enqueue_test/Enqueue.inot @@ -0,0 +1,13 @@ +void setup() { + // put your setup code here, to run once: + +} + +int i = 0; + +void loop() { + // Continuously pump counter + delay(100); + i++; + counter = i; +} diff --git a/examples/Enqueue_test/Enqueue_test.ino b/examples/Enqueue_test/Enqueue_test.ino new file mode 100644 index 0000000..c0f3b1d --- /dev/null +++ b/examples/Enqueue_test/Enqueue_test.ino @@ -0,0 +1,15 @@ +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + while (!Serial) {} + Enqueue.start(); + Serial.println("start"); +} + +void loop() { + // put your main code here, to run repeatedly: + delay(1000); + for (int i = 0; i < 10; i++) { + Serial.println(counter); + } +} diff --git a/examples/Enqueue_test/SharedVariables.h b/examples/Enqueue_test/SharedVariables.h new file mode 100644 index 0000000..51ea60e --- /dev/null +++ b/examples/Enqueue_test/SharedVariables.h @@ -0,0 +1 @@ +Shared counter;