D 2.0 FAQ on `shared`

Sean Kelly via Digitalmars-d digitalmars-d at puremagic.com
Tue Oct 21 09:56:57 PDT 2014


On Tuesday, 21 October 2014 at 16:36:30 UTC, Marc Schütz wrote:
>
> I think `shared` by itself is fine, as long as it is only take 
> to mean "this method can cope with the parameters being 
> shared". It's `synchronized` and casting that cause the 
> trouble, because they are too coarse, and synchronized doesn't 
> specify which parts of an object it protects. This makes more 
> detailed compiler checks impossible.

I think "synchronized" should work basically the same way.  For
example:

class C {
      int u;
      shared int s;
      shared Mutex m;

      void doSomething() shared { // can be called from a shared
reference
          u = 5; // error, u is not labeled as shared and operation
not synchronized
          s = 5; // ok, though maybe should require 
s.atomicStore(5)

          synchronized(m) {
              u = 5; // ok
              doSomething2(); // okay because labeled synchronized
          }
      }

      void doSomething2() synchronized { // can be called within a
synchronized block
          u = 5; // ok because synchronized
          s = 5; // ok, though maybe should require 
s.atomicStore(5)
      }
}


I'd like to avoid having a synchronized label on a method
implicitly lock anything because object monitors are terrible and
should not exist, and because even if the compiler tries to
optimize away recursive locking it won't always happen and the
result will be too expensive for anyone to actually want to use
it.


More information about the Digitalmars-d mailing list