Hi I have been working with RTOS environments for some time now (FreeRTOS and Zephyr) and I was wondering if, generally speaking, RTOS timers are considered more lightweight than threads. I am inclined to say yes because timers dont require their own stack space, context switching overheads, etc. What I mean is that a thread with a periodic blocking sleep/delay can be thought of as being more or less "equivalent" to a timer with the same period, right (at least in terms of scheduling)? So if given the choice between a thread based implementation and a timer based implementation - which one would you prefer?
To give a more concrete example: right now I am working on a Nordic chip (running Zephyr RTOS) wired to a vibration motor via a GPIO line. Pulsing the GPIO high/low causes the motor to vibrate. When the motor is vibrating which could be for upto several seconds, I don't want the thread that the invokes the vibration to block. The way I see it I have two options:
If timers are indeed lightweight, should I go for the timer-based implementation everytime? Is there perhaps a better way to go about this. Thanks!
You're right, RTOS timers are indeed more lightweight than threads because they don't require allocated stack memory and are generally simpler to implement and use. I personally tend to use timers over threads when the tasks are very short (e.g. periodic tasks or timeouts). I tend to use threads for longer tasks especially those that sometimes need to "run in parallel" to the rest of the system. I also sometimes tend to use threads for more modular and cleaner design (e.g. I can have a separate thread for UART operation, a speparate thread for BLE, etc).
For your specific use case, I would go for the timer simply because it doesn't seem complex or long enough in duration to warrant a separate thread. The operation you're doing is deterministic and periodic (toggling GPIO with a fixed delay) and therefore having a timer seems like the more logical option to me within the context of your functionality. If you foresee additional functionality being added when doing the vibrations, then at that time you can switch to using threads instead.