Updated Mar 2025
xSemaphoreTake
semphr. h
1 xSemaphoreTake( SemaphoreHandle_t xSemaphore,2 TickType_t xTicksToWait );
Macro to obtain a semaphore. The semaphore must have previously been created with a call to
xSemaphoreCreateBinary()
xSemaphoreCreateMutex()
xSemaphoreCreateCounting()
This macro must not be called from an ISR.
xQueueReceiveFromISR()
Parameters:
-
xSemaphore
A handle to the semaphore being taken - obtained when the semaphore was created.
-
xTicksToWait
The time in ticks to wait for the semaphore to become available. The macro
can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. If INCLUDE_vTaskSuspend is set to '1' then specifying the block time asportTICK_PERIOD_MSwill cause the task to block indefinitely (without a timeout).portMAX_DELAY
Returns:
- pdTRUE if the semaphore was obtained.
- pdFALSE if expired without the semaphore becoming available.xTicksToWait
Example usage:
1SemaphoreHandle_t xSemaphore = NULL;23/* A task that creates a semaphore. */4void vATask( void * pvParameters )5{6 /* Create the semaphore to guard a shared resource. As we are using7 the semaphore for mutual exclusion we create a mutex semaphore8 rather than a binary semaphore. */9 xSemaphore = xSemaphoreCreateMutex();10}1112/* A task that uses the semaphore. */13void vAnotherTask( void * pvParameters )14{15 /* ... Do other things. */1617 if( xSemaphore != NULL )18 {19 /* See if we can obtain the semaphore. If the semaphore is not20 available wait 10 ticks to see if it becomes free. */21 if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )22 {23 /* We were able to obtain the semaphore and can now access the24 shared resource. */2526 /* ... */2728 /* We have finished accessing the shared resource. Release the29 semaphore. */30 xSemaphoreGive( xSemaphore );31 }32 else33 {34 /* We could not obtain the semaphore and can therefore not access35 the shared resource safely. */36 }37 }38}