Getting correct value from Interlocked operations?

L

Lucian Wischik

William Stacey said:
That would work if those where exposed in the framework. It would be a
simple thing (I would think) for them to wrap that, however, and expose a
typed bool api.

Or, for Interlocked.Xor, you could use Interlocked.Increment and
examine only the lowest bit...
 
W

William Stacey [C# MVP]

| The hardware instruction can make the data available to all CPUs, but
| that isn't going to help if a thread has, for instance, loaded the
| value of a variable into a register at the start of a method and has no
| need (as far as the memory model is concerned) to reread the value from
| memory.

But now we talking about a different issue - no?
 
W

William Stacey [C# MVP]

I would think in most cases you would still want an atomic test and set. As
many times you want to know the value before setting it - atomically.
Otherwise you will need a read outside of the interlocked, which could
result in a race we are trying to avoid. So I think you still need two
methods to round the api out:

Interlocked.Exchange<bool>(ref value, T value) // unconditional set.
Interlocked.CompareExchange<bool>(ref T value, T comp, T value); //
conditional set.

So you could:

private bool started = true;
public void Stop()
{
// Set started to false if true. Set exactly once.
if ( Interlocked.CompareExchange<bool>(ref this.started, false,
true) )
return;
throw new Exception("Already stopped");
}

--
William Stacey [C# MVP]

| >That would work if those where exposed in the framework. It would be a
| >simple thing (I would think) for them to wrap that, however, and expose a
| >typed bool api.
|
| Or, for Interlocked.Xor, you could use Interlocked.Increment and
| examine only the lowest bit...
|
| --
| Lucian
 
J

Jon Skeet [C# MVP]

William Stacey said:
| The hardware instruction can make the data available to all CPUs, but
| that isn't going to help if a thread has, for instance, loaded the
| value of a variable into a register at the start of a method and has no
| need (as far as the memory model is concerned) to reread the value from
| memory.

But now we talking about a different issue - no?

Not that I'm aware of. I was talking about making sure that when you
read a value, it was correct at that point in time. If the read
occurred a long time ago and then was just enregistered, that isn't the
case. With a volatile variable, however, the read will always get the
"latest" value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top