CMSIS-RTOS2  Version 2.0.0
Real-Time Operating System: API and RTX Reference Implementation
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
Semaphores

Access shared resources simultaneously from different threads. More...

Data Structures

struct  osSemaphoreAttr_t
 Attributes structure for semaphore. More...
 

Typedefs

typedef void * osSemaphoreId_t
 

Functions

osSemaphoreId_t osSemaphoreNew (uint32_t max_count, uint32_t initial_count, const osSemaphoreAttr_t *attr)
 Create and Initialize a Semaphore object. More...
 
const char * osSemaphoreGetName (osSemaphoreId_t semaphore_id)
 Get name of a Semaphore object. More...
 
osStatus_t osSemaphoreAcquire (osSemaphoreId_t semaphore_id, uint32_t timeout)
 Acquire a Semaphore token or timeout if no tokens are available. More...
 
osStatus_t osSemaphoreRelease (osSemaphoreId_t semaphore_id)
 Release a Semaphore token that was acquired by osSemaphoreAcquire. More...
 
uint32_t osSemaphoreGetCount (osSemaphoreId_t semaphore_id)
 Get current Semaphore token count. More...
 
osStatus_t osSemaphoreDelete (osSemaphoreId_t semaphore_id)
 Delete a Semaphore object. More...
 

Description

Semaphores are used to manage and protect access to shared resources. Semaphores are very similar to Mutexes. Whereas a Mutex permits just one thread to access a shared resource at a time, a semaphore can be used to permit a fixed number of threads to access a pool of shared resources. Using semaphores, access to a group of identical peripherals can be managed (for example multiple DMA channels).

Semaphore.png
CMSIS-RTOS Semaphore

A semaphore object should be initialized to the maximum number of available tokens. This number of available resources is specified as parameter of the osSemaphoreNew function. Each time a semaphore token is obtained with osSemaphoreAcquire, the semaphore count is decremented. When the semaphore count is 0, no semaphore token can be obtained. The thread that tries to obtain the semaphore token needs to wait until the next token is free. Semaphores are released with osSemaphoreRelease incrementing the semaphore count.

Note
Semaphore tokens can be acquired from threads and released from threads and ISRs.
Refer to Semaphore Configuration for RTX5 configuration options.

Working with Semaphores

Follow these steps to create and use a semaphore:

  1. Declare the semaphore container and initialize the semaphore:
    osSemaphoreId_t my_semaphore_id
  2. Initialize the semaphore container with a number of tokens within a thread:
    my_semaphore_id = osSemaphoreNew(4, 0, NULL); // Create semaphore with 4 tokens
    Important: semaphore tokens can be created and destroyed as threads run. This means that can initialize a semaphore with zero tokens and then use one thread to add/create tokens to the semaphore while a second thread removes them. In this way you can distinguish between producer and consumer threads.
  3. Acquire a token from the semaphore container:
  4. When finished using the semaphore resource, send the token back to the semaphore container:
    osSemaphoreRelease(my_semaphore_id);

Semaphore Use Cases

Due to their flexibility, semaphores cover a wide range of synchronizing applications. At the same time, they are perhaps the most challenging RTOS object to understand. The following explains a use case for semaphores, taken from the book The Little Book Of Semaphores by Allen B. Downey which is available for free download.

Non-binary Semaphore (Multiplex)

A multiplex limits the number of threads that can access a critical section of code. For example, this could be a function accessing DMA resources which can only support a limited number of calls.

To allow multiple threads to run the function, initialize a semaphore to the maximum number of threads that can be allowed. The number of tokens in the semaphore represents the number of additional threads that may enter. If this number is zero, then the next thread trying to access the function will have to wait until one of the other threads exits and releases its token. When all threads have exited the token number is back to n. Ths following example shows the code for one of the threads that might access the resource:

osSemaphoreId_t multiplex_id;
void thread_n (void)
{
multiplex_id = osSemaphoreNew(3, 0, NULL);
while(1)
{
// do something
osSemaphoreRelease(multiplex_id);
}
}

Data Structure Documentation

struct osSemaphoreAttr_t
Data Fields
const char * name name of the semaphore
uint32_t attr_bits attribute bits
void * cb_mem memory for control block
uint32_t cb_size size of provided memory for control block

Typedef Documentation

Semaphore ID identifies the semaphore.

Function Documentation

osSemaphoreId_t osSemaphoreNew ( uint32_t  max_count,
uint32_t  initial_count,
const osSemaphoreAttr_t attr 
)
Parameters
[in]max_countmaximum number of available tokens.
[in]initial_countinitial number of available tokens.
[in]attrsemaphore attributes; NULL: default values.
Returns
semaphore ID for reference by other functions or NULL in case of error.

Create and initialize a Semaphore object that is used to manage access to shared resources. The parameter count specifies the number of available resources. The max_count value 1 creates a binary semaphore.

Code Example

#include "cmsis_os2.h"
osThreadId_t tid_thread1; // ID for thread 1
osThreadId_t tid_thread2; // ID for thread 2
osSemaphoreId_t semaphore; // Semaphore ID
//
// Thread 1 - High Priority - Active every 3ms
//
void thread1 (void *argument) {
while (1) {
osDelay(3); // Pass control to other tasks for 3ms
val = osSemaphoreAcquire (semaphore, 1); // Wait 1ms for the free semaphore
if (val > 0) {
// If there was no time-out the semaphore was acquired
: // OK, the interface is free now, use it.
osSemaphoreRelease (semaphore); // Return a token back to a semaphore
}
}
}
//
// Thread 2 - Normal Priority - looks for a free semaphore and uses
// the resource whenever it is available
//
void thread2 (void *argument) {
while (1) {
osSemaphoreAcquire (semaphore, osWaitForever); // Wait indefinitely for a free semaphore
// OK, the interface is free now, use it.
:
osSemaphoreRelease (semaphore); // Return a token back to a semaphore.
}
}
void StartApplication (void) {
semaphore = osSemaphoreNew(osSemaphore(semaphore), 1);
tid_thread1 = osThreadCreate(thread1, NULL, NULL);
tid_thread2 = osThreadCreate(thread2, NULL, NULL);
:
}
const char * osSemaphoreGetName ( osSemaphoreId_t  semaphore_id)
Parameters
[in]semaphore_idsemaphore ID obtained by osSemaphoreNew.
Returns
name as NULL terminated string.
osStatus_t osSemaphoreAcquire ( osSemaphoreId_t  semaphore_id,
uint32_t  timeout 
)
Parameters
[in]semaphore_idsemaphore ID obtained by osSemaphoreNew.
[in]timeoutTimeout Value or 0 in case of no time-out.
Returns
status code that indicates the execution status of the function.

Wait until a Semaphore token becomes available and acquires it for the thread if available. When no Semaphore token is available, the function waits for the time specified with the parameter timeout.

The argument timeout specifies how long the system waits for a Semaphore token to become available. While the system waits the thread that is calling this function is put into the state BLOCKED. The millisec timeout can have the following values:

  • when timeout is 0, the function returns instantly.
  • when timeout is set to osWaitForever the function will wait for an infinite time until the Semaphore token becomes available.
  • all other values specify a time in kernel ticks for a timeout.

The return value indicates the number of available tokens (the semaphore count value). If 0 is returned, then no semaphore was available.

osStatus_t osSemaphoreRelease ( osSemaphoreId_t  semaphore_id)
Parameters
[in]semaphore_idsemaphore ID obtained by osSemaphoreNew.
Returns
status code that indicates the execution status of the function.

Release a Semaphore token. This increments the count of available semaphore tokens.

osStatus_t return values:

  • osOK: the semaphore has been released.
  • osErrorResource: all tokens have already been released.
  • osErrorParameter: the parameter semaphore_id is incorrect.
uint32_t osSemaphoreGetCount ( osSemaphoreId_t  semaphore_id)
Parameters
[in]semaphore_idsemaphore ID obtained by osSemaphoreNew.
Returns
number of tokens available.

Returns the count of available semaphores of the semaphore object specified by semaphore_id.

osStatus_t osSemaphoreDelete ( osSemaphoreId_t  semaphore_id)
Parameters
[in]semaphore_idsemaphore ID obtained by osSemaphoreNew.
Returns
status code that indicates the execution status of the function.

Delete a Semaphore object. The function releases internal memory obtained for Semaphore handling. After this call the semaphore_id is no longer valid and cannot be used. The Semaphore may be created again using the function osSemaphoreNew.

osStatus_t return values:

  • osOK: the semaphore object has been deleted.
  • osErrorISR: osSemaphoreDelete cannot be called from interrupt service routines.
  • osErrorResource: the semaphore object could not be deleted.
  • osErrorParameter: the parameter semaphore_id is incorrect.
Note
Cannot be called from Interrupt Service Routines. Calling osSemaphoreDelete from an ISR will return osErrorISR.