I am just looking for feedback (obvious flaws/ways to improve it) on my attempt to implement atomic read/writes on a structure.
There will be one writing thread and multiple reading threads. The aim is to prevent a reader from getting an inconsistent view of the structure whilst not impeding the writer too much.
I am using the fetch-and-add atomic primitive, in this case provided by the Qt framework.
For example:
/* global */
OneWriterAtomicState<Point> atomicState;
/* Writer */
while(true) {
MyStruct s = atomicState.getState()
s.x += 2; s.y += 2;
atomicState.setState(s);
}
/* Reader */
while(true) {
MyStruct s = atomicState.getState()
drawBox(s.x,s.y);
}
OneWriterAtomicState Implementation:
template <class T>
class OneWriterAtomicState
{
public:
OneWriterAtomicState()
: seqNumber(0)
{
}
void setState(T& state) {
/* Due to the QAtomicInt memory ordering semantics, if the reader
ever encounters an ODD sequence number it can be assumed
that state is inconsistent.
After the state mutation has finished, the sequence number
is made EVEN again and can be safely read.
*/
this->seqNumber.fetchAndAddOrdered(1);
this->state = state;
this->seqNumber.fetchAndAddOrdered(1);
}
T getState(){
T result;
int seq;
bool seq_changed = true;
/* repeat while seq is ODD or if seq changes during read operation */
while( (seq=this->seqNumber.fetchAndAddOrdered(0)) & 0x01 || seq_changed ) {
result = this->state;
seq_changed = (this->seqNumber.fetchAndAddOrdered(0)!=seq);
}
return result;
}
private:
QAtomicInt seqNumber;
T state;
}
No comments:
Post a Comment