Are threads efficient?


I’m wondering to know if threads are efficient. This is a total newbie question, I know… But I am uncertain if it is the best choice for my project

I’m developing a device that have some LEDs and a buzzer. Put the code of these components in a separated thread (daemon) makes a lot of sense to me: a global variable selects which while loop with the behavior is executed.

I’m using a WROOM32 module and a only have two threads: the main thread and the peripherals’ thread. Can WROOM32 easily handle still more threads?

Best regards.

multi-threaded programming is used to max CPU utilization and to achieve concurrency (to execute multiple threads “together”).
Furthermore, multithreaded is an overhead for the CPU with each thread/task has its own stack, RAM,state… so I don’t think its suitable for your application.
I think finite state machines are more suitable for your application, making multiple states and a function that choose which state should run next.

1 Like

Thank you for this explanation, @karimhamdy1 ! In fact, the first version of my device uses an 8-bit microcontroller and I had implemented a state machine on it. It’s working well. Then I discovered Zerynth, which allowed me to make a new version effortless.

One thread handles with the HMI display, GPS module, calculations, etc. The GPS signal (1 Hz) trigger the actions on this thread. The other thread handles with the behavior of LEDs and buzzer (some PWMs to soft blink and different tones), and this is one of the new features of this version.

When I put all the code in a single thread, I noticed some “choking” in the operation of the LEDs and buzzer. When I use two threads, it works fawless. I noticed a small increment in the power consumed, but since my device isn’t battery-powered, I’m not concerned about it.

But so I think that I need to optimize my state machine code

1 Like