M
Michi Henning
Hi, I can't find a statement about this in the threading
sections in the doc...
Consider:
class Class1
{
Class1()
{
_val = 42;
}
public int getVal()
{
return _val;
}
private readonly int _val;
}
In a threaded environment, is it necessary to interlock
inside the constructor and getVal() to ensure that
threads get the correct value? In other words,
do I have to write it as follows?
class Class1
{
Class1()
{
lock(this)
{
_val = 42;
}
}
public int getVal()
{
lock(this)
{
return _val;
}
}
private readonly int _val;
}
In C++, the lock is necessary because, on SMP
machines, memory consistency isn't guaranteed without
the lock. But I don't know whether the same is true
for C#.
What if the member variable is not readonly (but will
never be modified, except for the initial assignment
in the constructor)? Is accessing the value thread-safe
without a lock in that case?
What about const members? Is access to those safe without
a lock?
And what about static members that are (conceptually)
immutable? Is the lock required there?
Thanks muchly,
Michi.
sections in the doc...
Consider:
class Class1
{
Class1()
{
_val = 42;
}
public int getVal()
{
return _val;
}
private readonly int _val;
}
In a threaded environment, is it necessary to interlock
inside the constructor and getVal() to ensure that
threads get the correct value? In other words,
do I have to write it as follows?
class Class1
{
Class1()
{
lock(this)
{
_val = 42;
}
}
public int getVal()
{
lock(this)
{
return _val;
}
}
private readonly int _val;
}
In C++, the lock is necessary because, on SMP
machines, memory consistency isn't guaranteed without
the lock. But I don't know whether the same is true
for C#.
What if the member variable is not readonly (but will
never be modified, except for the initial assignment
in the constructor)? Is accessing the value thread-safe
without a lock in that case?
What about const members? Is access to those safe without
a lock?
And what about static members that are (conceptually)
immutable? Is the lock required there?
Thanks muchly,
Michi.