Distributed semaphore

Hi, I’m starting in the FreeRTOS world and I need help. I want create a semaphore and use in many files to prevents concurrency problem. But I dont know how is the best practice to do this. I think to create a library that control the semaphores. Something like this:

<SemaphoresUtils.cpp>
static SemaphoreHandle_t semaphoreUart0;

void semaphoreUart0Create() {
semaphoreUart0 = xSemaphoreCreateMutex();
}

void semaphoreUart0Take()
{
xSemaphoreTake(semaphoreUart0, portMAX_DELAY);
}

void semaphoreUart0Give()
{
xSemaphoreGive(semaphoreUart0);
}

So, I will use this functions (semaphoreUart0Take() and emaphoreUart0Give()) in all my code. Its a good way to work?

It depends a lot on the usage of what you are protecting with the semaphore/mutex (and a mutex is somewhat better if it is mutual exclusion you are trying to achieve, which you code does seem to be using).

If it is global data that is accesses from many points, then it is probably the simplest to just make the semaphore/mutex handle global and use it as needed around the accesses.

If the access to the data/device is already bundled in to a library (or can easily be so done) then keeping the semaphore/mutex in the library is better.

1 Like