[Mono-devel-list] Thread safety of readonly data members?

Michi Henning michi at zeroc.com
Tue Feb 17 20:36:28 EST 2004


I have a question regarding thread safety...

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 (only initialized in the constructor and
never assigned again)? Is the lock required there?

Any difference in memory consistency models between
Mono and .NET? (I need to write code that is portable
to both platforms.)

Thanks muchly,

Michi.





More information about the Mono-devel-list mailing list