Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 7 months ago.
Semaphores vs. Signals
I've been working on a project using the mbed-rtos library, and one of the stumbling blocks I've been encountering is the proper use of semaphores. Now, I know the standard answer is something like "semaphores are just mutexes for a pool of resources", but according to this guy, this guy, and this guy, it's not that simple. To sum them all up: apparently mutexes have owners and semaphores do not (which is why mutexes can't be used in ISRs). This, along with a few other reasons, apparently means that semaphores are supposed to be used for signaling rather than protecting:
Quote:
The correct use of a semaphore is for signaling from one task to another. A mutex is meant to be taken and released, always in that order, by each task that uses the shared resource it protects. By contrast, tasks that use semaphores either signal or wait—not both. For example, Task 1 may contain code to post (i.e., signal or increment) a particular semaphore when the "power" button is pressed and Task 2, which wakes the display, pends on that same semaphore. In this scenario, one task is the producer of the event signal; the other the consumer.
This use case is also described in this forum topic, where Tyler Weaver suggests using a semaphore to block a task until an interrupt occurs:
wrote:
You can wait on an interrupt. Just use a semaphore.
Semaphore sem_adc(0); // in the thread that waits... sem_adc.wait(); // in the interrupt sem_adc.release();
This, however, flies in the face of the official semaphore example program, which just uses one like a mutex with two "slots". And to complicate things further, there's a signals example program which accomplishes the same thing using "signals", yet another RTOS primitive.
So my question at this point, is which one should I actually be using for signaling? Are semaphores better because they can count multiple events? Are signals a CMSIS-RTOS specific primitive that's not always available in other operating systems? I'm very confused right now...
1 Answer
10 years, 7 months ago.
With signals you must provide thread id , with semaphores you don't have. Also you could use queues similar to semaphores for signaling and waiting.