D const enables multi-reader synchronization

Tomek Sowiński just at ask.me
Mon Jun 14 13:49:36 PDT 2010


Dnia 14-06-2010 o 21:27:24 Brad Roberts <braddr at slice-2.puremagic.com>  
napisał(a):

> On Mon, 14 Jun 2010, Tomek Sowi?ski wrote:
>
>> This is a continuation of a recent thread "Synchronized const methods"  
>> on
>> D.learn.
>>
>> Currently only one thread at a time can execute a synchronized method.  
>> But
>> think about D's const -- it's deep, so if a method is const, it can't  
>> possibly
>> mutate its object. So many synchronized const method calls could safely
>> look-but-not-touch the same object at the same time.
>>
>> The chain of questions that stems from the above is:
>> 1. Is letting many readers in on an object really safe? Know any
>> multi-threading quirk that would make sh*t hit the fan?
>> 2. If answer to 1. is yes, would there be room in the current  
>> implementation
>> of synchronized keyword for a readers-writer lock?
>> 3. If answer to 2. is yes, how do we tackle write-starvation? In a  
>> read-mostly
>> scenario the mutating thread may be held up forever.
>>
>> More on readers-writer lock:
>> http://en.wikipedia.org/wiki/Readers-writer_lock
>>
>>
>> Tomek
>
> Const methods only prevent mutating 'this'. You can still call functions
> that mutate other state (via globals or passed in arguments).

But synchronized on a method also protects only 'this', no?. Currently you  
can have:

class A { ... }

shared class K {
     synchronized void fun(A a) const {
         // mutate a
     }
}

If you call fun on two instances of K, each in a different thread, but  
pass them the same instance of A, you'll get a data race anyway. You could  
make fun's arguments const, but still there's shared globals.

> Additionally, I'm also a little concerned about the implications to
> application performance.  Add one method that's non-const and suddenly  
> the
> app performs somewhat differently and it's hard to tell why.
>
> It's an interesting idea, and still worth exploring, but my inclinations
> are that this should be explicitly setup rather than done behind the
> scenes.

Probably. It's difficult to find info on threading in D2, so it's hard to  
imagine how a library implementation could look like.


Tomek


More information about the Digitalmars-d mailing list