Hi I'm trying to figure out when to use events vs. semaphores. It seems that when semaphore max count == 1, it's the same as an event in case 1, but not in case 2. Here are a few use cases.
1. Main task initializes several other tasks, or several copies of the same task, then waits for each one to post its semaphore. Main task has to wait N times for N tasks to finish posting. Not sure if this is the right way to do this sort of thing. Sounds like I can use either events or semaphores here:
main_task(...) {
_task_create(0, DEVICE_RUN_TASK, (uint32_t)(&semaphore0)); | |
_task_create(0, TIMER_TASK, (uint32_t)(&semaphore1)); | |
_task_create(0, TIMER_TASK, (uint32_t)(&semaphore2)); |
// Wait for start semaphores to come back, one per task. | |
_lwsem_wait(&semaphore0); | |
_lwsem_wait(&semaphore1); | |
_lwsem_wait(&semaphore2); |
}
2. Several slave tasks are waiting for master task to complete something. Master task has to post multiple semaphores, which is not good because the task should be agnostic of who's listening, and anyway the semantics are that all the slave tasks should see the event as an atomic thing, ie simultaneously, if only in theory and not in practice. So it sounds like I must use an event. Not sure how to ensure that each waiting task sees the same event at most exactly once. Is this what autoclearing is for?
Hi Michael,
Well, there is not a rule for implementing with either semaphores or events. In both cases I would say that the event is the best approach. It is because the event can be one action or more. You can configure 3 flags in an event( 0x0111). Then you set each event by different actions or different tasks (0x0001, 0x0010, 0x0100).
I believe you will find this webinar very interesting:
Essentials of MQX RTOS Application Development, Session 4: Synchronization and Message Passing
Regards,
Garabo
-----------------------------------------------------------------------------------------------------------------------
Note: If this post answers your question, please click the Correct Answer button. Thank you!
-----------------------------------------------------------------------------------------------------------------------
Thanks, I have decided to use semaphores to signal the main task that each sub-task has finished its initializing, and events to signal many tasks that a particular thing has happened. I’ll check out the webinar.
Thanks
michael