Using C++ with an RTOS

If your embedded application makes use of a real-time operating system [RTOS], like Nucleus, you will need to learn the API – the Application Program Interface. The API is a series of function calls that enable the application code to make use of the facilities provided by the RTOS. These facilities include control of tasks, timing, inter-task communication and synchronization and memory management. The number of available calls may run into hundreds, as a modern RTOS offers a wide range of functionality.

Although C is the most widely used language for programming embedded systems, many developers are keen to use C++. This opens up an alternative way to interface with an RTOS …

Because a modern RTOS tends to have a lot of functionality, the API calls may be quite complex. This can be daunting to inexperienced developers. It may be argued that most engineers do not need to know the details of RTOS operations and should concentrate on their specific area of expertise. This is where C++ can be a great help. In this, and some further postings in the coming few weeks, I will outline how C++ may be used to hide the unnecessary complexity and make an RTOS easier [and safer] to use. Toady, I will at a very simple way to take advantage of C++ functionality to write more solid and readable code.

It is quite common in embedded code – particularly real-time applications – to have a need for “paired operations”. These are complimentary actions, which must be performed as a pair. Examples include enable/disable of interrupts, device lock/unlock and memory allocation/deallocation.

Sometimes, it is necessary to write some “critical” code, which must complete without interruption. One way to achieve this is by disabling interrupts before the code and re-enabling them afterwards. This is OK so long as the re-enable actually occurs. In C++ we can create a class that helps:

class critical

An object instantiated from this class will cause interrupts to be disabled when it is created and re-enabled when it is destroyed [i.e. goes out of scope]. Thus, we can code a critical section by placing the relevant code in a block, which has a local object instantiated from the class critical, like this:

... // normal code

   critical section;
      // critical code goes here

... // back to normal code

The object/variable section is just a dummy – just a means to guarantee the execution of the constructor and destructor – but yields quite readable code.


Post Author

Posted February 20th, 2017, by

Post Tags

, , , , , , ,

Post Comments

No Comments

About The Colin Walls Blog

This blog is a discussion of embedded software matters - news, comment, technical issues and ideas, along with other passing thoughts about anything that happens to be on my mind. The Colin Walls Blog

@colin_walls tweets

Follow colin_walls


Add Your Comment