When is "volatile" used instead of "lock" ?

B

Ben Voigt [C++ MVP]

Jon Skeet said:
I think we may be talking at cross-purposes. I'm talking about a
situation which is theoretically possible in the CLI model, but not in
the .NET 2.0 model:

public class Foo
{
public int Bar; // Yeah, but with a property etc

public Foo(int b)
{
Bar = b;
}
}


Thread 1: Thread 2:
sharedVar = new Foo(10);
Console.WriteLine(sharedVar.Bar);


In theory (with the ECMA model), sharedVar's new value can be visible
to thread 2 before the write to sharedVar.Bar - meaning that thread 2
could end up printing "0".

That has been tightened up in the .NET 2.0 memory model.

That's related to the result of the new expression, though, not visibility
of the new reference. What if the Foo constructor had "sharedVar = this;"?
 
J

Jon Skeet [C# MVP]

Ben Voigt said:
That's related to the result of the new expression, though, not visibility
of the new reference.

Well, it's the result of the new reference becoming visible before all
the writes in the constructor are necessarily visible.
What if the Foo constructor had "sharedVar = this;"?

Then you could have an equally nasty situation.
 

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