RTOS and C++

One key thing you need to watch out for when using an RTOS like FreeRTOS is that you have a compatilbe library (library functions can handle being reentrant). Most parts of the library don’t have an issue with this. One of the big issues is heap management. In embeded C, you can fairly easy manage this yourself by either not using the heap, or changing calls to malloc to use the FreeRTOS wrappers. In C++ though, the new operator tends to call malloc itself directly. Out of the box, this may not be safe, as if another thread is doing the same you can corrupt your heap. Thare are a couple of ways around this:

1) Don’t use new in tasks. (including classes that internally use new) Many embeded design rules limit the use of the heap functions to initialization. This means that all dynamic objects are created before starting the schduler. This is one trip up in C++, as typical usage does much more heap usage than C, and much of it under the hood. 2) Wrap all calls that might use the heap in some form of exclusion (like a mutex or schedule suspend). This lets you use the heap, but does require care to identify all points that might use the heap (like adding/removing items from containers) 3) Override all the various operator new()s and operator delete()s to go through the wrappers. 4) If the library supports it, implement the reentriency layer for the library. For example, newlib provides a set of entry points to allow you to provide an exclusion object for malloc/calloc/realloc/free making them thread safe. (I think there is code for this in the core or example with a define to enable). These hooks also sometimes also create some thread local storage to make some other non-reentrent functions thread safe.

I use C++ at times with FreeRTOS (and a pointer to my wrapper class was posted above), and often I just use the first method, yes, it says I don’t use all of C++, but it is enough to get a lot of work done and use a lot of the improvements from C++, it says you don’t use the STL, but in an embeded enviroment where you can’t afford to get an out of memory fault in the middle of an operation, that becomes a design requirment anyway. I have used the 4th option in very limited cases.