Updated Jun 2025
xSemaphoreCreateMutex
semphr. h
1SemaphoreHandle_t xSemaphoreCreateMutex( void )
Creates a mutex, and returns a handle by which the created mutex can be referenced. Mutexes cannot be used in interrupt service routines.
configSUPPORT_DYNAMIC_ALLOCATION and configUSE_MUTEXES must both be set to 1 in FreeRTOSConfig.h for
xSemaphoreCreateMutex()
configSUPPORT_DYNAMIC_ALLOCATION
Each mutex require a small amount of RAM that is used to hold the mutex's state. If a mutex is created using
xSemaphoreCreateMutex()
Mutexes are taken using xSemaphoreTake(), and given using xSemaphoreGive().
xSemaphoreTakeRecursive()
xSemaphoreGiveRecursive()
Mutexes and binary semaphores are very similar but have some subtle differences: Mutexes include a priority inheritance mechanism, binary semaphores do not. This makes binary semaphores the better choice for implementing synchronisation (between tasks or between tasks and an interrupt), and mutexes the better choice for implementing simple mutual exclusion.
The priority of a task that 'takes' a mutex will be temporarily raised if another task of higher priority attempts to obtain the same mutex. The task that owns the mutex 'inherits' the priority of the task attempting to 'take' the same mutex. This means the mutex must always be 'given' back - otherwise the higher priority task will never be able to obtain the mutex, and the lower priority task will never 'disinherit' the priority. For more on the priority inheritance mechanism see the FreeRTOS Mutex documentation page
An example of a mutex being used to implement mutual exclusion is provided on the xSemaphoreTake() documentation page.
A binary semaphore need not be given back once obtained, so task synchronisation can be implemented by one task/interrupt continuously 'giving' the semaphore while another continuously 'takes' the semaphore. This is demonstrated by the sample code on the xSemaphoreGiveFromISR() documentation page. Note that the same functionality can be achieved in a more efficient way using a direct to task notification.
Handles to both mutexes and binary semaphores are assigned to variables of type
SemaphoreHandle_t
Returns:
-
If the mutex type semaphore was created successfully then a handle to the created mutex is returned.
-
If the mutex was not created because the memory required to hold the mutex could not be allocated then NULL is returned.
Example usage:
1SemaphoreHandle_t xSemaphore;23void vATask( void * pvParameters )4{5 /* Create a mutex type semaphore. */6 xSemaphore = xSemaphoreCreateMutex();78 if( xSemaphore != NULL )9 {10 /* The semaphore was created successfully and11 can be used. */12 }13}