As embedded systems developers, we are often constrained in the APIs and libraries that we can use in our programs. Many library creators assume a full-fledged computer environment and build their software on top of other host-machine libraries. This works extremely well until an embedded developer tries to port the software to a bare metal system – we often quickly find out that there are other dependencies or assumptions that we haven’t ported, don’t want to port, or can’t feasibly meet on our system.

Unfortunately the C++ STL falls into the “built for host machines” category. There are many useful features in the STL that are upon pthreads or other support that is not always implemented for bare metal systems. However, I still want to use the C++ STL on my embedded systems, and with a little bit of work we can make that happen.

Today we’ll start with an implementation of std::mutex using ThreadX RTOS primitives. Even if you aren’t using ThreadX, you can generalize this approach to the RTOS of your choice. Next week I’ll also provide a std::mutex implementation using the increasingly popular FreeRTOS.

Table of Contents

A Review of ThreadX Mutex Support

The ThreadX RTOS provides a the mutex type TX_MUTEX . The ThreadX mutex is implemented as a recursive mutex, so we will use the same type and functions for both the std::mutex and std::recursive_mutex implementations.

ThreadX uses four functions to interact with the mutex:

UINT tx_mutex_create(TX_MUTEX* ptr, const char* name, UINT inherit); UINT tx_mutex_delete(TX_MUTEX *ptr); UINT tx_mutex_get(TX_MUTEX* ptr, ULONG wait_option); UINT tx_mutex_put(TX_MUTEX* ptr);

Each mutex can be given a name and priority inheritance option during creation. Two inheritance values are defined:

#define TX_INHERIT 1 #define TX_NO_INHERIT 0

If TX_INHERIT is supplied during mutex creation, priority inheritance will be enabled for the mutex. Lower-priority threads will temporarily assume the priority of a higher-priority thread that is waiting for the mutex owned by the lower priority thread. If TX_NO_INHERIT is supplied during mutex creation, priority inheritance will not be enabled.

Note: Generally we want priority inheritance to be enabled to prevent priority inversions or deadlocks.

The tx_mutex_get function uses the wait_option parameter. The wait_option argument is used to set a timeout for getting the mutex. Two standard wait options are defined by ThreadX:

#define TX_NO_WAIT 0 #define TX_WAIT_FOREVER ((ULONG) 0xFFFFFFFF)

If TX_NO_WAIT is supplied, tx_mutex_get will immediately return and report whether or not getting the mutex was successful.

If TX_WAIT_FOREVER is supplied, the thread will block until the mutex is successfully acquired.

If a value other than TX_NO_WAIT or TX_WAIT_FOREVER is supplied, it is interpreted as a timeout. The thread will block until the specified number of ticks have elapsed or the mutex was successfully locked.

Success in any of the functions is indicated by a return code of TX_SUCCESS . Other return codes indicate failure.

Implementing std::mutex with ThreadX

Now that we’ve familiarized ourselves with the ThreadX mutex APIs, let’s get started with our std::mutex port.

Before we can dive into the code, we need to find ourselves a working set of C++ files to start from. I recommend the LLVM libc++ implementation.

To get the LLVM libc++ files, you can perform an svn checkout:

svn co http://llvm.org/svn/llvm-project/libcxx/trunk libcxx

The entire std::mutex implementation encompasses the following files:

mutex (header)

(header) __mutex_base (header)

(header) __threading_support (header, defines underlying mutex types)

(header, defines underlying mutex types) mutex.cpp

We’ll be making minor modifications to the files above and creating our own definitions for the underlying mutex types.

If you don’t want to start from scratch, you can always modify the example mutex files from my embedded-resources repository for your RTOS.

About libc++ Threading Abstractions

We’ll start our std::mutex port by exploring the __threading_support file. This file defines the underlying libc++ threading types and shim functions for std::mutex and friends, std::thread , and std::condition_variable .

Luckily the threading code is easily decoupled from the underlying pthread implementation. If you look inside the __threading_support header, you’ll notice that we can supply our own __external_threading header to override the default definitions:

#if defined(_LIBCPP_HAS_THREAD_API_EXTERNAL) # include <__external_threading>

We will use this __external_threading header to re-implement the threading types and shim functions for our target RTOS.

Creating our __external_threading header

First we need to create our __external_threading header. I’m interested in building a C++ library that supports multiple RTOSes, so I will be implementing a two-header system. The basic __external_threading header will re-route the compiler to another header based on the RTOS I am targeting. For now we will just populate it with our ThreadX definitions:

#ifndef _LIBCPP_EXTERNAL_THREADING_SUPPORT #define _LIBCPP_EXTERNAL_THREADING_SUPPORT #if THREADX #include <__external_threading_threadx> #endif #endif //_LIBCPP_EXTERNAL_THREADING_SUPPORT

If you are only supporting a single RTOS, feel free to skip the layer of redirection.

Populating __external_threading_threadx

We’ll create the __external_threading_threadx file for storing our custom threading definitions.

First we’ll include the tx_api.h header:

#include <threadx/tx_api.h>

I also included some of the boilerplate definitions from the start of the __threading_support header:

#if defined(__FreeBSD__) && defined(__clang__) && __has_attribute(no_thread_safety_analysis) #define _LIBCPP_NO_THREAD_SAFETY_ANALYSIS __attribute__((no_thread_safety_analysis)) #else #define _LIBCPP_NO_THREAD_SAFETY_ANALYSIS #endif _LIBCPP_BEGIN_NAMESPACE_STD #define _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_FUNC_VIS

Supplying the mutex definitions for ThreadX is straightforward:

// Mutex typedef TX_MUTEX __libcpp_mutex_t; //TX_MUTEX is a struct, so we need a struct initializer #define _LIBCPP_MUTEX_INITIALIZER {0} typedef TX_MUTEX __libcpp_recursive_mutex_t;

We’re not quite ready to port std::condition_variable or std::thread yet, so we’ll import the generic type definitions from the “no pthread API” case in __threading_support :

// Condition Variable typedef void* __libcpp_condvar_t; #define _LIBCPP_CONDVAR_INITIALIZER 0 // Execute Once typedef void* __libcpp_exec_once_flag; #define _LIBCPP_EXEC_ONCE_INITIALIZER 0 // Thread ID typedef long __libcpp_thread_id; // Thread #define _LIBCPP_NULL_THREAD 0U typedef void* __libcpp_thread_t; // Thread Local Storage typedef long __libcpp_tls_key; #define _LIBCPP_TLS_DESTRUCTOR_CC __stdcall

In coming articles we’ll work on porting std::thread and possibly std::condition_variable , so these definitions will be updated. For now I’m just focused on std::mutex .

I also imported the shim function prototypes from __threading_support :

// Mutex _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_recursive_mutex_init(__libcpp_recursive_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS int __libcpp_recursive_mutex_lock(__libcpp_recursive_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS bool __libcpp_recursive_mutex_trylock(__libcpp_recursive_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS int __libcpp_recursive_mutex_unlock(__libcpp_recursive_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_recursive_mutex_destroy(__libcpp_recursive_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS int __libcpp_mutex_lock(__libcpp_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS bool __libcpp_mutex_trylock(__libcpp_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS int __libcpp_mutex_unlock(__libcpp_mutex_t *__m); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_mutex_destroy(__libcpp_mutex_t *__m);

I also imported the std::thread and std::condition_variable shims so the compiler will be happy:

// Condition variable _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_condvar_signal(__libcpp_condvar_t* __cv); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_condvar_broadcast(__libcpp_condvar_t* __cv); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS int __libcpp_condvar_wait(__libcpp_condvar_t* __cv, __libcpp_mutex_t* __m); _LIBCPP_THREAD_ABI_VISIBILITY _LIBCPP_NO_THREAD_SAFETY_ANALYSIS int __libcpp_condvar_timedwait(__libcpp_condvar_t *__cv, __libcpp_mutex_t *__m, timespec *__ts); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_condvar_destroy(__libcpp_condvar_t* __cv); // Execute once _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_execute_once(__libcpp_exec_once_flag *flag, void (*init_routine)(void)); // Thread id _LIBCPP_THREAD_ABI_VISIBILITY bool __libcpp_thread_id_equal(__libcpp_thread_id t1, __libcpp_thread_id t2); _LIBCPP_THREAD_ABI_VISIBILITY bool __libcpp_thread_id_less(__libcpp_thread_id t1, __libcpp_thread_id t2); // Thread _LIBCPP_THREAD_ABI_VISIBILITY bool __libcpp_thread_isnull(const __libcpp_thread_t *__t); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_thread_create(__libcpp_thread_t *__t, void *(*__func)(void *), void *__arg); _LIBCPP_THREAD_ABI_VISIBILITY __libcpp_thread_id __libcpp_thread_get_current_id(); _LIBCPP_THREAD_ABI_VISIBILITY __libcpp_thread_id __libcpp_thread_get_id(const __libcpp_thread_t *__t); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_thread_join(__libcpp_thread_t *__t); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_thread_detach(__libcpp_thread_t *__t); _LIBCPP_THREAD_ABI_VISIBILITY void __libcpp_thread_yield(); _LIBCPP_THREAD_ABI_VISIBILITY void __libcpp_thread_sleep_for(const chrono::nanoseconds& __ns); // Thread local storage _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_tls_create(__libcpp_tls_key* __key, void(_LIBCPP_TLS_DESTRUCTOR_CC* __at_exit)(void*)); _LIBCPP_THREAD_ABI_VISIBILITY void *__libcpp_tls_get(__libcpp_tls_key __key); _LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_tls_set(__libcpp_tls_key __key, void *__p);

Implementing the Recursive Mutex Shims

The recursive mutex shim functions are just wrappers around our underlying ThreadX mutex calls:

int __libcpp_recursive_mutex_init(__libcpp_recursive_mutex_t *__m) { return tx_mutex_create(__m, "std::recursive_mutex", TX_INHERIT); } int __libcpp_recursive_mutex_lock(__libcpp_recursive_mutex_t *__m) { //tx mutex is already recursive return tx_mutex_get(__m, TX_WAIT_FOREVER); } bool __libcpp_recursive_mutex_trylock(__libcpp_recursive_mutex_t *__m) { //intentional no wait for try_lock return tx_mutex_get(__m, TX_NO_WAIT) == TX_SUCCESS; } int __libcpp_recursive_mutex_unlock(__libcpp_mutex_t *__m) { return tx_mutex_put(__m); } int __libcpp_recursive_mutex_destroy(__libcpp_recursive_mutex_t *__m) { return tx_mutex_delete(__m); }

Implementing the Mutex Shims

Since ThreadX has no distinction between a recursive and non-recursive mutex, our mutex shim functions look exactly the same:

int __libcpp_mutex_lock(__libcpp_mutex_t *__m) { return tx_mutex_get(__m, TX_WAIT_FOREVER); } bool __libcpp_mutex_trylock(__libcpp_mutex_t *__m) { //intentional no wait for try_lock return tx_mutex_get(__m, TX_NO_WAIT) == TX_SUCCESS; } int __libcpp_mutex_unlock(__libcpp_mutex_t *__m) { return tx_mutex_put(__m); } int __libcpp_mutex_destroy(__libcpp_mutex_t *__m) { return tx_mutex_delete(__m); }

Breaking with the Standard: Initializing std::mutex

Unfortunately, we’ll need to break with the standard to support std::mutex with an RTOS.

The default mutex implementation assumes you can create your mutex with the default value:

#define _LIBCPP_MUTEX_INITIALIZER {0}

The std::mutex constructor assumes the mutex can be created by supplying the default initialization value:

mutex() _NOEXCEPT {__m_ = (__libcpp_mutex_t)_LIBCPP_MUTEX_INITIALIZER;}

We need to call a function to initialize our mutex. This function might fail, and if it does we should throw an exception. Since std::recursive_mutex has an initialization function and can throw, I’ve decided to break with the standard on this point. (I’m still investigating why things have been set up this way…)

We’ll define a new definition in our __external_threading_threadx header that can control the behavior of the std::mutex constructor:

// TX_MUTEX requires a function to initialize #define _MUTEX_REQUIRES_INITIALIZATION 1

We’ll also define a new mutex shim function that our constructor can call:

_LIBCPP_THREAD_ABI_VISIBILITY int __libcpp_mutex_init(__libcpp_mutex_t *__m); int __libcpp_mutex_init(__libcpp_mutex_t *__m) { return tx_mutex_create(__m, "std::mutex", TX_INHERIT); }

Modifying __mutex_base

In order to support our custom shim function, we will need to modify the __mutex_base header.

If _MUTEX_REQUIRES_INITIALIZATION is defined and equal to 1, we will want to call our custom constructor. Otherwise we want to implement the default behavior.

Unfortunately, the need to initialize our std::mutex means we cannot use the constexpr constructor, so we are deviating from the C++ standard.

We’ll adjust the std::mutex constructor logic to meet this behavioral requirement:

#if defined(_MUTEX_REQUIRES_INITIALIZATION) && (_MUTEX_REQUIRES_INITIALIZATION == 1) // We currently deviate from the standard on this point // Since some of our mutexes require dynamic initialization mutex() _NOEXCEPT; #else #ifndef _LIBCPP_CXX03_LANG constexpr mutex() = default; #else mutex() _NOEXCEPT {__m_ = (__libcpp_mutex_t)_LIBCPP_MUTEX_INITIALIZER;} #endif

I am investigating alternative methods to satisfy the constexpr requirement. Unfortunately, it might require initialization when calling lock() .

Modifying mutex.cpp

The shim functions are called in mutex.cpp , so we need to add our std::mutex constructor there. The constructor should only be included if _MUTEX_REQUIRES_INITIALIZATION is set.

#if defined(_MUTEX_REQUIRES_INITIALIZATION) && (_MUTEX_REQUIRES_INITIALIZATION == 1) mutex::mutex() { int ec = __libcpp_mutex_init(&__m_); if (ec) __throw_system_error(ec, "mutex constructor failed"); } #endif

And that completes the port! Thanks to a well-designed shim layer, we didn’t need to do too much work at all.

Building Our Custom std::mutex

A few compilation options need to be set in order to build std::mutex with support for ThreadX. Since a variety of build systems are in use, I am only providing general build strategies.

First, we’ll need to set _LIBCPP_HAS_THREAD_API_EXTERNAL so that the compiler looks for the __external_threading header.

-D _LIBCPP_HAS_THREAD_API_EXTERNAL

If you’re using the __external_threading implementation that will support multiple RTOSes, you’ll also need to set a THREADX definition:

-DTHREADX=1

You’ll also want to set the following compiler flags so that the default C++ libraries are not linked:

-fno-builtin -nodefaultlibs

As well as the following link options:

-nodefaultlibs

Because we didn’t include all the cpp headers, we need to point our compiler to the include location for other C++ headers. Make sure your local path is placed ahead of the mainstream path so that your compiler picks it up first.

Here’s an example if you’re compiling with clang on OSX:

-I/path/to/src/include -I/usr/local/opt/llvm/include/c++/v1/

Putting It All Together

I’ve included my example std::mutex implementation in the embedded-resources GitHub repository. The implementation can be found in examples/libcpp .

The example is currently built as a static library. Only ThreadX headers are included in the repository, so the current example is only runnable if you have a ThreadX implementation.

To compile the example, simply run:

cd examples/libcpp make

In a coming article I will walk through a std::mutex implementation using FreeRTOS.

Further Reading