Embedded device -> std::thread -> FreeRTOS?

2.3k Views Asked by At

so currently i am investigating the possibility in using a pure C++17 Project for an embedded device (Cortex m4). But based on the fact that it is an embedded device we have port and use an RTOS Such as FreeRTOS or uc-OS and i would highly prefer in using the std::thread (So we can easily exchange the RTOS if it is required). Is there a way to override the thread class in C++ to use the platform depended RTOS?

Thanks in advance

2

There are 2 best solutions below

1
NathanOliver On

There is no way to tell std::thread to use use FreeRTOS::thread (made this up) but you can use conditional compilation and a type alias like

#ifdef FREE_RTOS                  // you will need to get the correct symbol from the implementation to check for
using thread_t = FreeRTOS::thread // you will need to use the correct type here
#elif defined(OTHER_RTOS)
using thread_t = OtherRTOS::thread
#else
using thread_t = std::thread
#endif

And n ow thread_t will be the thread type from the implementation and falls back to std::thread if no symbols are found.

1
aep On

Is there a way to override the thread class in C++ to use the platform depended RTOS?

There's no easy way to do this, but there have been attempts to do so by others as pointed out by @Arthur Passo. Even that's not simply overriding the OS specific classes, instead you need to hook toochain calls to look at the FreeRTOS api whenever OS specific call is needed. This would in turn raises so many questions about keeping things maintainable across different compiler versions.

Since I have been doing a similar sort of investigation a few months ago, I reckon the best possible solution would be one of the following. (I would personally stick to option 1 given the amount of flexibility and convenience in maintenance).

  1. Make your own C++ OS abstraction layer on top of CMSIS OS API which most of RTOS providers support(FreeRTOS, KeilRTX, Chibi support it, I am sure uc-OS does it as well). This makes it easier to use a single abstraction with many RTOSes as long as your build system is capable of linking the proper files depending upon the RTOS being used. This at the same time gives you full flexibility to configure thread priorities, stack sizes etc. which might not be possible if you go with something like posix api.

  2. Make your own C++ OS abstraction layer on top of POSIX api. FreeRTOS provides a POSIX API https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_POSIX/index.html, I'm sure others will have a similar variant of it.