Hello all,
I am trying to understand which one (mutex, semaphore, or queue) is the best choice for any scenario. As I see it, a mutex is best suited to protect a shared resource, a semaphore is best suited for waking up a task when an event occurs, and a queue is used to share data.
For example, suppose a temperature and humidity sensor sends data to the MCU over UART. We have two tasks: a Sensor Task that receives the sensor data and a Terminal Task that sends the received data to a serial terminal over another UART.
My first thought is to use a queue because the Sensor Task needs to pass the temperature and humidity data to the Terminal Task.
I also thought about using a mutex. My concern is that if both tasks access the same global structure, the Sensor Task might update the temperature value and then get preempted before updating the humidity value. If the Terminal Task runs at that moment, it could read the new temperature but the old humidity value, resulting in inconsistent data. I think a mutex would solve this problem by allowing only one task to access the shared structure at a time, ensuring that the Terminal Task always reads a complete and consistent set of data.
So, for this scenario, what would be your preferred approach? Would you use only a queue, only a mutex, or a combination of both? My initial thought is to use a queue along with a mutex, because I feel that using either a queue or a mutex alone may not solve the entire problem.
Do you agree with my approach? If not, could you give me the reason why not?