basic concurrency

kris foo at bar.com
Tue Apr 18 10:25:20 PDT 2006


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.

For situations where high throughput is a concern, you'd likely want to 
use a lock-free design instead. There's not many of those around since 
they're tricky to write -- however, as John noted earlier, there's a 
port of Doug Lea's ConcurrentHashMap available; it gets by with no locks 
at all, in the general cases. Makes it a really good choice where thread 
contention is evident.



More information about the Digitalmars-d-learn mailing list