Working on a IoT device (Linux, ARM, C++). Right now I am creating boilerplate code and general program structure. The program communicates to different hardware:
- GPIO pins on the board.
- Several 1-wire sensors.
- Additional GPIO chips and keys on the I2C bus.
- Device connected via RS232 interfaces
Now the tricky part is that RS232 devices, 1-wire and I2C devices are not that quick to respond. It means that if I do something like this on a single thread:
while (!_isShutdown)
{
for (auto& device : _devices)
{
device.update();
}
}
I would waste a lot of time and resources, even more so, I would unable to complete my task in time because several sensors may take up to 500ms to retrieve the latest value.
This issue naturally led me to multithreading. I can a background thread for each device. It means that the more devices I have, the more threads and memory (I believe 1MB) I would use. In my case it may take up to 30 threads just to manage hardware (I have a network communication as well which means even more threads).
I thought that maybe there exist a better approach for hardware management. Maybe creating a thread each time a read execution blocks is a bad design? If so, what are the alternatives? There are many simple examples on the Internet, but few useful materials on complex projects.
On devices like Raspberry memory and execution speed is not an issue, but that could to a bad habit of developing stupid and unoptimized code. I ask you to clarify this.