basic concurrency

Frank Benoit keinfarbton at nospam.xyz
Tue Apr 18 09:16:47 PDT 2006


> 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.



More information about the Digitalmars-d-learn mailing list