I have a multi-threaded c++ program that performs some intensive on-going calculations.
I want the program to write the progress to the GUI/console as the calculation progresses.
To do so I have the threads set some data regarding their individual progress, which the main thread periodically checks in order to determine how much of the total calculation has been completed.
Each thread is assigned a separate piece of data to write to (i.e. element of a std::vector
) so no two pieces of data have more than one thread writing to them.
However the main thread must also read these data and thus concurrency is an issue. If two threads access the same data and at least one is a write operation that can lead to a data race which is undefined behavior.
Currently I am preventing this with a single mutex, but I am concerned that this is slowing my program down unnecessarily.
Which makes me wonder - the value of the concurrently used data is not critical to the program logic - so could I, in principle, remove the data race protections (the mutex) - allow data races to happen - and simply manually check to see if the written values are garbage before doing anything with them? Or does the very nature of a data race existing cause wider undefined behavior that could break my problem?
Or is there another, better way, of doing this? Off the top of my head another option would be a vector of atomics such that at least each thread has a distinct concurrency protection so that they are not treading on each other, so to speak.