What is the output of the following FreeRTOS code snippet that uses taskENTER_CRITICAL() and taskEXIT_CRITICAL()?
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> volatile int shared_counter = 0; void increment_counter() { taskENTER_CRITICAL(); shared_counter++; taskEXIT_CRITICAL(); } int main() { increment_counter(); increment_counter(); printf("%d\n", shared_counter); return 0; }
Think about what taskENTER_CRITICAL() and taskEXIT_CRITICAL() do to the shared variable.
The taskENTER_CRITICAL() disables interrupts to protect the critical section, so the increment operation on shared_counter is safe and not interrupted. Calling increment_counter() twice increases the counter from 0 to 2.
What is the main purpose of using taskENTER_CRITICAL() in FreeRTOS?
Think about what needs to be prevented during a critical section.
taskENTER_CRITICAL() disables interrupts and task switching to ensure that the code inside the critical section runs without interruption, preventing race conditions.
Consider the following code snippet. What error will occur when running this code?
void update_shared() {
taskENTER_CRITICAL();
shared_var++;
// Missing taskEXIT_CRITICAL();
}
int main() {
update_shared();
return 0;
}What happens if interrupts stay disabled forever?
Because taskEXIT_CRITICAL() is missing, interrupts remain disabled, causing the system to freeze or deadlock as no interrupts can occur.
Which option contains a syntax error when using taskENTER_CRITICAL() and taskEXIT_CRITICAL()?
void func() {
taskENTER_CRITICAL()
shared_var++;
taskEXIT_CRITICAL();
}Check each line for missing punctuation.
taskENTER_CRITICAL() is a macro or function call and must end with a semicolon. Missing it causes a syntax error.
What is the value of shared_counter after running the following code?
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> volatile int shared_counter = 0; void nested_critical() { taskENTER_CRITICAL(); shared_counter++; taskENTER_CRITICAL(); shared_counter++; taskEXIT_CRITICAL(); taskEXIT_CRITICAL(); } int main() { nested_critical(); printf("%d\n", shared_counter); return 0; }
Consider how nested critical sections behave in FreeRTOS.
FreeRTOS supports nesting of critical sections. Each taskENTER_CRITICAL() increments a nesting count and disables interrupts only once. The shared_counter increments twice safely, so the final value is 2.
