In FreeRTOS, why does using a mutex help prevent data corruption when multiple tasks access the same variable?
Think about what happens if two friends try to write on the same paper at the same time.
A mutex ensures that only one task can access the shared resource at once. This prevents two tasks from changing the data at the same time, which could cause errors or corruption.
What will be the output of this FreeRTOS code snippet where two tasks increment a shared counter protected by a mutex?
int shared_counter = 0; SemaphoreHandle_t mutex; void Task1(void *params) { for (int i = 0; i < 5; i++) { xSemaphoreTake(mutex, portMAX_DELAY); shared_counter++; xSemaphoreGive(mutex); } vTaskDelete(NULL); } void Task2(void *params) { for (int i = 0; i < 5; i++) { xSemaphoreTake(mutex, portMAX_DELAY); shared_counter++; xSemaphoreGive(mutex); } vTaskDelete(NULL); } // After both tasks finish, what is shared_counter?
Each task increments 5 times, but the mutex prevents overlap.
Because the mutex ensures exclusive access, all increments happen without interference. So 5 increments from each task add up to 10.
Consider two FreeRTOS tasks incrementing a shared variable without a mutex. What error is most likely to happen?
int shared_var = 0; void TaskA(void *params) { for (int i = 0; i < 1000; i++) { shared_var++; } vTaskDelete(NULL); } void TaskB(void *params) { for (int i = 0; i < 1000; i++) { shared_var++; } vTaskDelete(NULL); } // What problem can occur here?
Think about what happens if two friends try to write the same number on a paper at the same time.
Without a mutex, both tasks can read, increment, and write back the variable simultaneously, causing some increments to be lost. This is called a race condition.
What is wrong with this FreeRTOS code snippet that uses a mutex to protect a shared resource?
SemaphoreHandle_t mutex; int shared_data = 0; void Task(void *params) { xSemaphoreTake(mutex, 0); shared_data++; xSemaphoreGive(mutex); vTaskDelete(NULL); } // Assume mutex was created before tasks start.
Check the meaning of the block time parameter in xSemaphoreTake.
Using 0 as block time means the task will not wait for the mutex if it is not available, so the take can fail and the shared_data increment happens without protection.
In FreeRTOS, when a low priority task holds a mutex needed by a high priority task, what mechanism helps avoid priority inversion?
Think about how the system can help the low priority task finish faster when a high priority task is waiting.
Priority inheritance temporarily raises the priority of the low priority task holding the mutex to the level of the high priority task waiting for it, preventing priority inversion.
