C
Chris Mullins [MVP]
I've got a quick question that's been bugging me for a long, long time:
Let's say I've got a member variable (in a heavily threaded app):
private int _firstTime = 0;
To make changes to this is easy enough:
InterlockedExchange(ref _firstTime, 1);
.... or I can use the InterlockedCompareExchange:
int oldValue = InterlockedCompareExchange(ref _firstTime, 1, 0);
No problems here.
.... but, if I just want to read the value, I CANNOT do:
int myValue = _firstTime;
or
if (_fistTime==0)
Doing these requires a memory barrier of some type (volatile variable,
monitor, etc) to have any degree of reliability.
Now, reading the value out using InterlockedCompareExchange always seemed a
bit silly to me. I don't want to always write:
int myValue = InterlockedCompareExchange(ref _firstTime, Int32.MinValue,
Int32.MinValue);
I've never found (although not for lack of looking):
int myValue = InterlockedRead(ref _firstTime);
Of the code that I write, reading the value, and branching based on it's
value, is much more common than writing to the value.
I have, in the past, used volitile variables for this - but I've stopped due
to the various issues regarding volatiles (non atomic reads & writes).
Is there a concensus on the best way to do this? It seems like all the
solutions are.... incomplete.
Essentially I'm looking for a volitile varaiable that is atomically read and
written. Unfortuantly, these don't exist in any language I've yet used.
Let's say I've got a member variable (in a heavily threaded app):
private int _firstTime = 0;
To make changes to this is easy enough:
InterlockedExchange(ref _firstTime, 1);
.... or I can use the InterlockedCompareExchange:
int oldValue = InterlockedCompareExchange(ref _firstTime, 1, 0);
No problems here.
.... but, if I just want to read the value, I CANNOT do:
int myValue = _firstTime;
or
if (_fistTime==0)
Doing these requires a memory barrier of some type (volatile variable,
monitor, etc) to have any degree of reliability.
Now, reading the value out using InterlockedCompareExchange always seemed a
bit silly to me. I don't want to always write:
int myValue = InterlockedCompareExchange(ref _firstTime, Int32.MinValue,
Int32.MinValue);
I've never found (although not for lack of looking):
int myValue = InterlockedRead(ref _firstTime);
Of the code that I write, reading the value, and branching based on it's
value, is much more common than writing to the value.
I have, in the past, used volitile variables for this - but I've stopped due
to the various issues regarding volatiles (non atomic reads & writes).
Is there a concensus on the best way to do this? It seems like all the
solutions are.... incomplete.
Essentially I'm looking for a volitile varaiable that is atomically read and
written. Unfortuantly, these don't exist in any language I've yet used.