www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - a different kind of synchronized

I have been thinking about this since some time.

When writing collections or similar I sometime want the object to be  
accessible from multiple threads, and sometime form only one.
Obviously I want the version that uses a single thread to be efficient.

To easily write both these version it would be really useful to be  
able to easily activate/deactivate with a flag some synchronization.

To do this the synchronized statement is bad because it synchronizes  
the following code, and thus cannot be switched off without switching  
off the code inside it.

A better solution would be

	synchronized(bla...);

which would mean synchronized starting here, i.e.

	monitor(bla).lock();
	scope(exit){ monitor(bla).unlock(); }

(only that getting the monitor is a bit more complicated).
As in D ";" is not a valid statement one would not have issues with  
the usual synchronized statement.
The advantage is that with this you can easily do something like

static if (shouldLock) synchronized(this);

and thus easily write lock protected versions of an object.

Fawzi
Nov 25 2010