The idea behind acquiring critical section by disabling interrupts

Basic question: how is the critical section established by merely disabling the interrupts assuming the interrupt isn’t fiddling with the data that you were accessing in the thread? Wouldn’t it only make sense to disable interrupts when it may modify the said value that you could be accessing somewhere else?

Disabling interrupts prevents context switches to another task that may access the same data. It is not the only method of doing that - you can also lock the scheduler, or lock the data even with a mutex or other method, but it is by way the fastest method if the critical section is very small.

If I understand your question correctly, it’s the same one that has been discussed here:

Disabling interrupts manually, not by taskENTER_CRITICAL() - Kernel - FreeRTOS Community Forums


Disabling interrupts prevents context switches to another task that may access the same data

really? Wouldn’t disabling interrupts ONLY result in disabling any other interrupts from firing? How is that preventing context switching between tasks?

A context switch between tasks is initiated by an interrupt. That interrupt (xPortSysTickHandler()) will also be disabled in a critical section.

Note that in some cases, only interrupts up to a certain priority level are disabled in a critical section. The higher-priority interrupts are not allowed to call any kernel API’s.

You don’t acquire the critical section by disabling interrupts. You just prevent being preempted/interrupted in a critical section by disabling interrupts.
It would be a good idea not to call OS services which might cause a context switch in a “critical section”! Under this assumption (meaning you didn’t write buggy code) you will not get a context switch in your critical section with interrupts disabled. Normally the timer tick interrupt will trigger the scheduler, which might trigger a context switch, but if you disable interrupts this will not happen.

1 Like

Ah, is it PendSV that causes interrupt to context switch? So basically, by disabling interrupts, we are not only disabling the external interrupts set up by the user but also the ones that are internal to FreeRTOS including the one causes context switching?

As @htibosch mentioned for some platforms like Cortex-M3/4…) only interrupts covered by FreeRTOS (limited by configMAX_SYSCALL_INTERRUPT_PRIORITY) are disabled. This includes the interrupts used by the scheduler, of course.
Key of a critical section is that it’s not preempted.