Reputation: 8874
I have a shared variable of type double
. This variable will be accessed by two threads. One thread will ever only write the variable, whereas the other thread will ever only read the variable.
Do I still get race condition here? If yes, is there an "easy" way in C++ to implement atomic access? How do I implement it efficiently if there is going to be much much more reads than writes? Do I need to mark the variable as volatile
?
EDIT: OK the "reader" thread works periodically on batches of data and the propagation of the new value is not time-sensitive. Instead of implementing complicated interlocking that I have no good way to test, I can just declare another temp variable the writer thread will write to. Then when the reader is finished with one batch, it can atomically propagate the temp value to the actual variable. Would that be race-condition-free?
Upvotes: 3
Views: 2200
Reputation: 283823
Yes, there's a race condition, since double
variables are not atomic on most processors.
Use 3 doubles (possibly an array with extra padding in between, to avoid false sharing that kills performance).
One is owned by the reader, one is owned by the writer, one is being handed off.
To write: write to the write slot, then atomically swap (e.g. with InterlockedExchange
) the pointer/index for the write slot with the index for the handoff slot. Since the index is pointer-sized or smaller, atomically swapping is easy as long as the variable is properly aligned. If by chance your platform offers interlocked-exchange with and without memory barriers, use the one with.
To read: atomically swap the pointer/index for the read slot with the index for the handoff variable. Then read the read slot.
You should actually include a version number also, since the read thread will tend to bounce between the latest and previous slot. When reading, read both before and after the swap, then use the one with the later version.
Or, in C++11, just use std::atomic
.
Warning: the above only works for single writer/single reader (the particular case in this question). If you have multiple, think about a reader-writer lock or similar protecting all access to the variable.
Upvotes: 8
Reputation: 5701
You might want to take a look at this that discusses reads/writes of primitive types:
Are C++ Reads and Writes of an int Atomic?
Upvotes: 0