Reputation: 11
I try to write a program for physical simulations. I use two threads, one for the calculations and one for the gui. To exchange data between them I use a struct
struct sim_data {
int running;
int steps;
int progress;
...
};
and include it in the different threads
void *sim(void *args) {
struct sim_data *my_data;
my_data=(struct sim_data *)args;
...
}
When setting a value by
my_data->progress=1000;
the data is available in the same thread but not reliably in the second thread. I would guess a chance of 10% when starting the program to read a different value in the second thread then writing in the first one. While the data is written in a loop, I don't think it's a timing problem.
I think this is very strange. Any guess what's going wrong?
Upvotes: 1
Views: 2388
Reputation: 3604
Simplest solution:
struct sim_data {
int running;
int steps;
atomic<int> progress; //this will guarantee the data are coherent between two threads
...
};
Upvotes: 0
Reputation: 10903
The C++11 specification declares a data race case to be any time when one thread writes to a location while a second thread can read or write to the same. It declares that you get undefined behavior when this occurs. In your case, one thread is writing to my_data->progress while another is reading it.
The solution is to use synchronization, such as atomic ints, or locking.
The C++ compiler does very impressive optimizations to make your single threaded programs run faster. For example, it may prove that, in a single threaded world, there is no way to see the 1000 value, and simply choose not to print it.
There's even more ugly cases that are legal. If the compiler knows that you wanted to store 1000, it might choose not to store anything at all, and instead use that memory as a space to 'spill' temporary results into it rather than allocating more space, before eventually storing the 1000. During the mean time, you may read ANY arbitrary value.
For a rather humorous view on the issue: http://software.intel.com/en-us/blogs/2013/01/06/benign-data-races-what-could-possibly-go-wrong
Upvotes: 1