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();
}
}
}
-------------------------------------------------------
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();
}
}
}
-------------------------------------------------------