Critical Section Behavior

gfvalvo
Posts: 36
Joined: Thu Dec 24, 2020 3:06 pm

Critical Section Behavior

Postby gfvalvo » Thu Nov 14, 2024 12:07 pm

Suppose that a Task on Core 1 has entered a Critical Section (i.e. taskENTER_CRITICAL(&lock)). Now suppose a Task (not an ISR) on Core 0 attempts to enter a Critical Section using the same lock object. Will that cause all of Core 0 to “hang” and spin waiting for lock to become available? Or, will that Core 0 Task simply block and wait for the lock to become available (similar to waiting for a Mutex)? The latter method would allow other Tasks and ISRs to continue running on Core 0 while the one Task blocks.

Thanks.

MicroController
Posts: 1724
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: Critical Section Behavior

Postby MicroController » Thu Nov 14, 2024 3:05 pm

gfvalvo wrote:
Thu Nov 14, 2024 12:07 pm
Will that cause all of Core 0 to “hang” and spin waiting for lock to become available?
Yes.
[blocking] would allow other Tasks and ISRs to continue running on Core 0 while the one Task blocks.
It would, but just switching out the blocked task and switching in another one takes thousands of CPU cycles, which is likely (in fact, should be) much longer than the critical section will be occupied by the other core.

If you explicitly want that blocking/yielding behavior, a FreeRTOS mutex or semaphore is what you're looking for.

Depending on what exactly you need to do atomically, you may want to consider using the types and functions from <stdatomic.h> (or <atomic> in C++), as these can translate to atomic operations implemented by the CPU, which can be much faster than entering and exiting a critical section.

If you're curious, you can then go on and research "lock-free data structures" a.k.a. "non-blocking algorithms" which leverage those atomic hardware operations to completely avoid using locks.

Who is online

Users browsing this forum: nullbert and 80 guests