basic concurrency

Tydr Schnubbis fake at address.dude
Tue Apr 18 16:18:51 PDT 2006


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.

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?



More information about the Digitalmars-d-learn mailing list