I’m trying to understand when a counting semaphore is the right choice in FreeRTOS.
My project was originally written in bare-metal using polling. It has two UART peripherals:
UART1 for terminal communication
UART2 for RFID reception
I’ve read that counting semaphores are used to manage multiple identical resources, which made me wonder whether these UARTs could be considered such resources. This has left me a bit confused about what exactly is meant by a resource in this context.
Would these UARTs be considered resources that could be managed with a counting semaphore, are counting semaphores more appropriate for other things.
If you don’t consider the UARTs to be suitable resources for a counting semaphore, could you also explain why not in my application.
Since the UARTS connect to different devices, they are not “identical”. A task presumably will care what is at the other end of the UART when it tries to communicate with it.
Suppose we have an EEPROM connected over I2C and the EEPROM is divided into fixed-size blocks. I have two tasks: one stores timestamps and another stores names. Whenever a task needs to save data, it can use any free EEPROM block; it doesn’t care which specific block it gets.
In that case, would the EEPROM blocks be considered identical resources and therefore be a reasonable use case for a counting semaphore?
My thinking is that a counting semaphore could track how many free blocks are available, while some other mechanism (bitmap, free list, etc.) would identify which specific block to use.
Does this sound like a valid use of a counting semaphore, or am I still misunderstanding the core concept?
That is a bit closer, but since you need to find the block to use, and searching might be time-consuming, and needing additional locks, for this application I would tend to use a queue where I store the block ID of “free” blocks. This is very much like a counting semaphore, only it includes some data with the count. In fact, FreeRTOS implements a counting semaphore as a queue of a given size that just doesn’t store any data.
I tend to think of a counting semaphore for multiple resourse that are so identical I don’t need to know which one I am using, though they can handle resources like you describe, if the determination of which resource is free is “cheap” enough.
I find they tend to work mostly for me for controlling “load levels”, and not specific resources. Perhaps you want to limit the number of compute-bound operations going on at once so they finish in a timely manner with less thrashing, or you want to limit the resource utilization on a resource outside your system, like the number of sockets open to another specific server.