Implementing std::mutex with FreeRTOS

Last week we looked at an implementation of std::mutex using the ThreadX RTOS. We will build upon the work in the previous article and add support for FreeRTOS.

In this edition, we will only be creating __external_threading definitions for FreeRTOS. If you are interested in the underlying work, please refer to the ThreadX RTOS port for more information.

Table of Contents

  1. A Review of FreeRTOS Mutex Support
  2. Implementing std::mutex with FreeRTOS
    1. Populating __external_threading_freertos
    2. Implementing the Recursive Mutex Shims
    3. Implementing the Mutex Shims
    4. Breaking with the Standard: Initializing std::mutex
  3. Building Our Custom std::mutex
  4. Putting It All Together
  5. Further Reading

A Review of FreeRTOS Mutex Support

Unlike ThreadX, FreeRTOS differentiates between recursive and non-recursive mutexes. However, FreeRTOS uses the SemaphoreHandle_t as a shared handle type for semaphores, mutexes, and recursive mutexes.

FreeRTOS uses the following APIs to interact with a non-recursive mutex:

SemaphoreHandle_t xSemaphoreCreateMutex( void );
SemaphoreHandle_t xSemaphoreCreateMutexStatic(
        StaticSemaphore_t *pxMutexBuffer );
xSemaphoreTake( SemaphoreHandle_t xSemaphore,
                 TickType_t xTicksToWait );
xSemaphoreGive( SemaphoreHandle_t xSemaphore );

FreeRTOS uses the following APIs to interact with a recursive mutex:

SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void );
SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic(
                     StaticSemaphore_t *pxMutexBuffer );
xSemaphoreTakeRecursive( SemaphoreHandle_t xMutex,
        TickType_t xTicksToWait );
xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex );

Both recursive and non-recursive mutexes use the same deleter function:

void vSemaphoreDelete( SemaphoreHandle_t xSemaphore );

When attempting to claim the mutex, both the recursive and non-recursive "Take" functions allow you to specify a number of ticks to wait before failing. A value of 0 indicates no waiting. Unlike ThreadX, there is no "wait forever", but FreeRTOS defines portMAX_DELAY to represent the longest timeout available on the system. Note that our "Take" calls can timeout over extremely long periods of time.

All of the mutex functions shown above are available when including the semphr.h header.

Implementing std::mutex with FreeRTOS

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

Thanks to a well-designed shim layer, we can build off of the ThreadX std::mutex implementation and focus only on the FreeRTOS shims.

We need to adjust our __external_threading file for FreeRTOS:

#ifndef _LIBCPP_EXTERNAL_THREADING_SUPPORT
#define _LIBCPP_EXTERNAL_THREADING_SUPPORT

#if THREADX
#include <__external_threading_threadx>
#elif FREERTOS
#include <__external_threading_freertos>
#endif

#endif //_LIBCPP_EXTERNAL_THREADING_SUPPORT

An alternative approach is to create an __external_threading file inside of separate include folders. When compiling for different RTOSes, you simply change the include path so that each RTOS implementation is paired with the correct __external_threading header.

Populating __external_threading_freertos

We'll create the __external_threading_freertos file for storing our custom threading definitions.

First we'll include the FreeRTOS and semaphore headers:

#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>

We'll include some boilerplate which is also defined in __threading_support:

#ifndef _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER
#pragma GCC system_header
#endif

_LIBCPP_PUSH_MACROS
#include <__undef_macros>

#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 FreeRTOS is straightforward:

// Mutex
typedef SemaphoreHandle_t __libcpp_mutex_t;

#define _LIBCPP_MUTEX_INITIALIZER 0

// FreeRTOS Mutex requires a function to initialize
#define _MUTEX_REQUIRES_INITIALIZATION 1

typedef SemaphoreHandle_t __libcpp_recursive_mutex_t;

Like the ThreadX std::mutex initialization, we'll need to use a non-constexpr constructor for std::mutex. We define _MUTEX_REQUIRES_INITIALIZATION to enable this support.

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, including our custom _libcpp_mutex_init function:

// 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
int __libcpp_mutex_init(__libcpp_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 FreeRTOS recursive mutex calls:

int __libcpp_recursive_mutex_init(__libcpp_recursive_mutex_t *__m)
{
  *__m = xSemaphoreCreateRecursiveMutex();

  return (*__m == NULL);
}

int __libcpp_recursive_mutex_lock(__libcpp_recursive_mutex_t *__m)
{
  return xSemaphoreTakeRecursive(*__m, portMAX_DELAY);
}

bool __libcpp_recursive_mutex_trylock(__libcpp_recursive_mutex_t *__m)
{
  //intentional no wait for try_lock
  return xSemaphoreTakeRecursive(*__m, 0);
}

int __libcpp_recursive_mutex_unlock(__libcpp_mutex_t *__m)
{
  return xSemaphoreGiveRecursive(*__m);
}

int __libcpp_recursive_mutex_destroy(__libcpp_recursive_mutex_t *__m)
{
  vSemaphoreDelete(*__m);

  return 0;
}

Implementing the Mutex Shims

The basic mutex shim functions are just wrappers around our underlying FreeRTOS non-recursive mutex calls:

int __libcpp_mutex_init(__libcpp_mutex_t *__m)
{
  *__m = xSemaphoreCreateMutex();

  return (*__m == NULL);
}

int __libcpp_mutex_lock(__libcpp_mutex_t *__m)
{
  return xSemaphoreTake(*__m, portMAX_DELAY);
}

bool __libcpp_mutex_trylock(__libcpp_mutex_t *__m)
{
  //intentional no wait for try_lock
 return xSemaphoreTake(*__m, 0);
}

int __libcpp_mutex_unlock(__libcpp_mutex_t *__m)
{
  return xSemaphoreGive(*__m);
}

int __libcpp_mutex_destroy(__libcpp_mutex_t *__m)
{
  vSemaphoreDelete(*__m);

  return 0;
}

Building Our Custom std::mutex

A few compilation options need to be set in order to build std::mutex with support for FreeRTOS. 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 FREERTOS definition:

-DFREERTOS=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 FreeRTOS headers are included in the repository, so the current example is only runnable if you have a FreeRTOS implementation.

To compile the example, simply run:

cd examples/libcpp
make

Further Reading