D locking strategies

estew estewh at gmail.com
Thu Mar 14 17:19:44 PDT 2013


Hi All,

I'm getting myself confused with thread-safety and locking. I 
have a class something like the following small example:

class A{
     private string[] _values;

     void setValue(size_t i, string val) {_values[i] = val;}
     string getValue(size_t i) conts {return _values[i];}
     const(string)[] getValues() const {return _values;}
     void setValues(in string[] c) const {_values = c;}

// Should I avoid @property ???
     @property const(string)[] values() const {return _values;}
     @property void values(in string[] vals) {_values = vals;}
}

To make it thread safe I have removed the @property and 
getValues/setValues (those which get/set the full array). This 
allows access via setValue(i, "val") or string val = getValue(i) 
only. However, if possible I would prefer not to do this. My 
thread-safe A has become:

class A{
     private string[] _values;
     void setValue(size_t i, string val)  {_values[i] = val;}
     string getValue(size_t i) const  {return _values[i];}
}


with 3 locking attempts implemented:

1. use rwmutex to gain read/write locking on the get/set functions
2. use synchronized on the entire class?
3. use synchronized on the _values field and then each get/set 
use synchronized?

Questions:
a) What is a good way to make this thread safe? One of the three 
attempts or something else?
b) I like @property because I find it makes code easier to read 
and write. But I hear they're going out of favour. Should I drop 
using @property?

Any help is appreciated.

Thanks,
Stewart


More information about the Digitalmars-d-learn mailing list