I am writing a Windows 10 application that collects data from 4 different sensors (encoders and IMUs) via serial. I am writing this in Visual Studio in c++11. I have one thread per sensor that continuously pulls data from it in an infinite loop.
As I am new to this, I am currently struggling to somehow 'collect' the data in a single thread. I have found that I can use conditional variables to signal another thread (in my case I assume I would be signaling the main thread when each sensor is complete). In this scenario, would I have to store the data in a global variable and protect it with a mutex as I write into it (from the sensor thread) and read from it (in the main loop)?
I worry, however, that this process may be too slow for my application (each sensor gets new data every 1-2 ms), and so in the process of locking the data while the main thread reads, I would lose some data. Would it make sense to (within each sensor thread) store the data in a local variable and then copy this variable to a global variable, and have the main thread only read from the 2nd variable?
I apologize if these are stupid questions, but I really need help. Any example code would be extremely appreciated.
I would handle this by using the boost::asio library to set up asynchronous reads on each sensor. When an asynchronous read completes, it calls a read handler to parse the data and then sets up another asynchronous read. All the read handlers run in the same thread - which makes life a lot simpler.