Custom Blocks

Chris Williams aahz at seanet.com
Mon Aug 9 18:39:37 PDT 2010


I'm not sure whether the design of D 2.0 has stabilized as yet, but if not,
I would like to suggest the ability to create custom block types.

For example, say that I have an object that I'm using in a multithreaded
application. In general, I would do something like:

synchronized (myObject) {
   ...fiddle with it
}

But, now I want to change myObject into being guarded by a read-write mutex.
By best option will be something like:

{
   myObject.readLock();
   scope (exit) myObject.readUnlock();
   ...check contents
}

{
   myObject.writeLock();
   scope (exit) myObject.writeUnlock();
   ...fiddle with it
}

I'd much rather be able to say:

readLock (myObject) {
   ...check contents
}

writeLock (myObject) {
   ...fiddle with it
}

It should be simple enough to add such functionality to D as it's little
different from templating. I'd tenatively propose a syntax like the
following, where the $ symbol is replaced with the contents of the block:

interface IRWLock {
   void readLock();
   void readUnlock();
   void writeLock();
   void writeUnlock();
}

block_template readLock(IRWLock o) {
   o.readLock();
   scope (exit) o.readUnlock();
   $
}

block_template writeLock(IRWLock o) {
   o.writeLock();
   scope (exit) o.writeUnlock();
   $
}

With local, hidden variables you would also be able to do something like:

block_template doOnce() {
   static bool hasRun = false;
   if (!hasRun) {
      hasRun = true;
      $
   }
}

int main() {
   while (true) {
      ...do stuff
      debug {
         doOnce {
            writefln("Value %s", foo);
         }
      }
      ...more stuff
      debug {
         doOnce {
            writefln("Value %s", bar);
         }
      }
   }
}


More information about the Digitalmars-d mailing list