Arduino Ring Buffer - Make it Thread Safe
Posted: Fri Jan 21, 2022 12:11 pm
Hello everyone. First time writing here but long time Arduino ESP32 stack user.
I have wrote a Ring Buffer with high level C++ and now I would like to be able to share that ring buffer between multiple writers and one reader. I would like to know how to avoid this situacion in ESP32-IDF (arduino stack):
1- Writer 1 is writing the ring buffer on a task 1
2- Task 1 is suspended before it finishes the write operation.
3- Task 2 resumes and writes to the ring buffer.
4- Ring buffer breaks....
The same goes for reading. Task 1 could be reading when Task 2 enters and writes to the ring buffer before Task 1 finished reading... that ends in data corruption...
I saw that I could use vTaskSuspendAll() xTaskResumeAll() but that would pause all the tasks in the same core. Is that enough? Is that the appropriate way to do this?
Can you recommend me a course of action on how to implement/re-implement this buffer so It can be shared between tasks and cores?
The Ring Buffer now it's a generic template that can handle any Type of element.
template <typename Type, uint32_t MaxElements>
class RingBuffer {
}
Thanks
Gonzalo
I have wrote a Ring Buffer with high level C++ and now I would like to be able to share that ring buffer between multiple writers and one reader. I would like to know how to avoid this situacion in ESP32-IDF (arduino stack):
1- Writer 1 is writing the ring buffer on a task 1
2- Task 1 is suspended before it finishes the write operation.
3- Task 2 resumes and writes to the ring buffer.
4- Ring buffer breaks....
The same goes for reading. Task 1 could be reading when Task 2 enters and writes to the ring buffer before Task 1 finished reading... that ends in data corruption...
I saw that I could use vTaskSuspendAll() xTaskResumeAll() but that would pause all the tasks in the same core. Is that enough? Is that the appropriate way to do this?
Can you recommend me a course of action on how to implement/re-implement this buffer so It can be shared between tasks and cores?
The Ring Buffer now it's a generic template that can handle any Type of element.
template <typename Type, uint32_t MaxElements>
class RingBuffer {
}
Thanks
Gonzalo