Critical Section


To go over Critical Sections in RTOS as well as other kernel API calls that, for the most part, you should refrain from using.

What are Critical Sections

Critical sections (also called critical regions) are sections of code that makes sure that only one thread is accessing resource or section of memory at a time.

Implementations of a critical section are varied. Many systems create critical sections using semaphores, but that is not the only way to produce a critical section.

How to Define a Critical Section

    /* Enter the critical section.  In this example, this function is itself called
    from within a critical section, so entering this critical section will result
    in a nesting depth of 2. */

    /* Perform the action that is being protected by the critical section here. */

    /* Exit the critical section.  In this example, this function is itself called
    from a critical section, so this call to taskEXIT_CRITICAL() will decrement the
    nesting count by one, but not result in interrupts becoming enabled. */

Code Block 1. Entering and Exiting a Critical Section (

Using the two API calls taskENTER_CRITICAL() and taskEXIT_CRITICAL(), one is able to enter and exit a critical section.

Implementation in FreeRTOS

Typically, when FreeRTOS is ported to a system, critical sections will STOP/DISABLE the OS Tick interrupt that calls the RTOS kernel.

If you task takes too long to do its operation, RTOS can perform in a real time manner because it has been shutdown during your critical section. Which is why you need to super selective about using a critical section.

The FreeRTOS implementation for Critical Sections by Espressive (ESP32 platform) does not RTOS, but actually uses a mutex that is passed in instead. It becomes an abstraction to using semaphore take and give API calls.

Critical Section VS Mutex

Choose a mutex when ever possible, but note that a critical section implementation is typically faster. If all you need to do is read or write to a few standard number data types quickly then a critical section can be utilized.

But a better alternative would be to evaluate the structure of your tasks and see if there is really a need to use a mutex or critical section.

Use a mutex when using a perpherial that you must wait for, like SPI, UART, I2C etc.

Back to top