Why FreeRTOS don't use atomic operations to implement a semaphore?

Hello everyone. I have one doubt about the choice of semaphore implementation on RTOS. My question is not a bug or like similar, is like a philosphy question to all the community (haha).

Microprocessors like ARM have atomic instructions to implement a mutex, so why implement your own logic using enable/disable interrupts to make the same logical thing like a atomic operation does. Portability between the different microprocessors?

Thank you.

Are you referring to the FreeRTOS semaphore, or the atomic operations header file?

If the former then FreeRTOS semaphores do more than just atomically set/clear values. They contain list of tasks waiting to ‘give’ the semaphore, a list of tasks waiting to ‘take’ the semaphore (both lists are ordered by priority first, and length of time waiting second), along with an event mechanism that enables a task to block either trying to give or take a semaphore and then automatically unblock when whichever event they are waiting for occurs (in accordance with the scheduling policy). There could be a very small benefit from using an atomic operation within that comprehensive functionality, but what a semaphore cannot do in FreeRTOS use cases is spin using an atomic operation until it can complete as doing so would starve lower priority tasks of processing time and so could potentially prevent the event the spinning task was waiting for.

I would say the biggest reason FreeRTOS doesn’t use such an instruction is that not all microprocessors have such an instruction, and even ones that do very in exactly what they provide. This means that for FreeRTOS to be cross platform, that core functionality would need to be moved to the port layer.

Also, these special atomic operations might provide a faster success path, but in the case of the fail path, you will still need the interrupt disable critical section to recheck the case and setup to block, so using the instruction actually increases code size and makes the code slower for the failure case.

I should add here that FreeRTOS does support a generic interface for atomic operations here https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/master/include/atomic.h and when they meet your needs you should absolutely use them and avoid the Semaphores as the latter would be a lot more expensive to achieve the same thing.

The idea is that ports that do not have those instructions will fall back to using standard FreeRTOS Semaphores as a last resort.

1 Like