Complete the code to take a semaphore before accessing a shared resource.
if (xSemaphoreTake(sem, [1]) == pdTRUE) { // Access shared resource xSemaphoreGive(sem); }
Using portMAX_DELAY makes the task wait indefinitely until the semaphore is available.
Complete the code to give the semaphore after finishing the critical section.
void task_function(void *params) {
if (xSemaphoreTake(sem, portMAX_DELAY) == pdTRUE) {
// Critical section code
[1](sem);
}
}After finishing the critical section, xSemaphoreGive() releases the semaphore so other tasks can take it.
Fix the error in the code to correctly take the semaphore with a timeout of 50 ticks.
if (xSemaphoreTake(sem, [1]) == pdTRUE) { // Critical section xSemaphoreGive(sem); }
The timeout parameter should be the number of ticks to wait, here 50 ticks.
Fill both blanks to check if the semaphore was successfully taken within 10 ticks.
if (xSemaphoreTake(sem, [1]) == [2]) { // Semaphore taken successfully }
The code waits 10 ticks and checks if the semaphore was taken successfully (pdTRUE).
Fill all three blanks to return the result of giving the semaphore only if the task took it successfully, else pdFALSE.
BaseType_t result = (xSemaphoreTake(sem, [1]) == [2]) ? xSemaphoreGive(sem) : [3];
The code waits indefinitely to take the semaphore, checks for success (pdTRUE), gives the semaphore if successful, else pdFALSE.
