In the following example, is the use of 'volatile' not needed.

G

Guest

Assume that this is running on a multiprocessor machine and multiple threads
are invoking both methods of the class below. Since I lock access to the
_value member, there should be no reason for me to mark _value as volitle.
Though, by marking it as volatile i will know that the program never read
the cached value from the cpu but in this case, but seeing how I placed lock
statements around the only 2 methods that exist in the class, which are the
only ways to read from or write to the private member _value, the scenario
that the volatile keyword prevents (reading of possibly old data) will never
occur. Can anyone confirm? Thx in advance.

---------------------------------------------------------------------------

public selaed class Foo
{

private static readonly object _locker;
private static volatile int _value;
static Foo()
{
_locker = new object();
}

static void GetCurrentValue()
{
lock(_locker)
{
return _value;
}
}

static void GenerateValue()
{
lock(_locker)
{
_value = new Random().Next();
}
}
}

-------------------------------------------------------
 
N

Nicholas Paldino [.NET/C# MVP]

Hasani,

You are right. Because you have the value in a lock block, you do not
have to worry about concurrent access or a cached value.

Hope this helps.
 
G

Guest

Thx very much for the confirmation!!!
Nicholas Paldino said:
Hasani,

You are right. Because you have the value in a lock block, you do not
have to worry about concurrent access or a cached value.

Hope this helps.
 

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