mercredi 30 août 2017

c++ - Sharing Data Among Threads

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.

Aucun commentaire:

Enregistrer un commentaire