Too illustrate how headconst can help with multithreading (shared memory) code, I have created this small snippet. In my experience, there are lots of *effectively immutable* objects (like Foo.bar in the code snippet). If these variables can be declared headconst, a lot of hierarchical synchronization locking (and therefor deadlock situations) can be saved. In the present Dlang semantics we do not have any specifier to make *effective mutability* effective. So presently I have to create a naming and coding discipline when declaring and using effectively mutable hierarchical objects.

class Bar {
  void funcBar() { }
}

class Frop {
  void funcFrop() { }
}

class Foo {
  this() {
    synchronized(this) {
      bar = new Bar();
    }
  }

  void setFrop() {
    frop = new Frop();
  }

  headconst Bar bar;            // effectively immutable
  Frop frop;                    // mutable

  void funcBar() {              // no locking required
    bar.funcBar();              // since bar is effectively immutable
  }

  void funcFrop() {
    synchronized(this) {        // lock necessary since frop
      frop.funcFrop();          // is mutable
    }
  }
}

void main() {
  Foo foo = new Foo();
  // yield for other threads
  // foo.setFrop();    // in some other thread
  foo.funcBar();
  foo.funcFrop();
}

Reply via email to