basic concurrency

kris foo at bar.com
Tue Apr 18 18:14:04 PDT 2006


Tydr Schnubbis wrote:
> kris wrote:
> 
>> Frank Benoit wrote:
>>
>>>> How do I use 'synchronized' to make sure get() and append() can't be
>>>> called simultaneously by two or more different threads?
>>>
>>>
>>>
>>>
>>> class MyArray {
>>>   private int[] array;
>>>
>>>   int get(size_t i){
>>>     synchronized(this){
>>>       return array[i];
>>>     }
>>>   }
>>>
>>>   void append(int v){
>>>     synchronized(this){
>>>       array ~= v;
>>>     }
>>>   }
>>> }
>>>
>>> the synchronized statement used the object instance reference of MyArray
>>> like a binary semaphore.
>>> It is guaranteed only one thread at a time and object can pass the
>>> barrier. I don't know, perhaps the "(this)" can be omitted.
>>
>>
>>
>> Like Frank said, you can prohibit simultaneous access by using the 
>> "synchronized" keyword (just like Java). His example shows 
>> synchronizing on a specific object, although you can also synch on the 
>> container:
>>
>> synchronized void get(size_t i) {
>>   ...
>> }
>>
>> In this case, the effect is the same in both examples.
> 
> 
> When one thread executes a synchronized, piece of code, can another 
> thread execute another piece of synchronized code?  The way I read the D 
> docs, it can.  But how can this work if that's true?  That only one 
> thread can execute the 'get' method at any given time doesn't help if 
> another thread at the same time can execute another method that modifies 
> the same array.

multiple threads can be executing sections of code at the same time, 
only if that code is guarded by different and distinct locks (or not 
guarded at all). The simple case of synch, with D objects, will protect 
each object instance against multi-thread collisions. Think of it as a 
per-object mutex.


> 
> And this syntax:
> synchronized void get(size_t i) {}
> 
> Does this allow get to be run only by one thread for all the objects of 
> the class, or one thread per object, like synchronized (this) {} does?

No -- it's per instance, like synchronized(this). If you want to synch 
across all class instances, then you could synch on the appropriate 
classinfo instead of 'this'.



More information about the Digitalmars-d-learn mailing list