www.digitalmars.com         C & C++   DMDScript  

D - synchronized

reply Sean Kelly <sean ffwd.cx> writes:
I'm wondering how this works at a lower level.  The first case seems 
self-explanatory: " synchronized allows only one thread at a time to 
execute Statement."  So I imagine I could do this:

synchronized
{
     // stuff
}

and only one thread could enter that block at a time.  But the second 
case is a bit trickier: "synchronized (Expression), where Expression 
evaluates to an Object reference, allows only one thread at a time to 
use that Object to execute the Statement."  Does this mean that the 
object is held exclusively by the thread until execution passes out of 
scope, or only that access is synchronized any time a thread attempts to 
read or write the object within that block?

I do have an unlterior motive--I'd like to get a condvar implementation 
in D.  The basic structure of condvars in D would probably look like this:

synchronized( var )
{
     while( var != desired )
         cond.wait( var );
}

But there are some subtle issues.  cond.wait _atomically_ releases the 
mutex protecting var and blocks and then atomically reacquires the mutex 
when it unblocks.  This is to allow multiple threads to wait on the same 
condition simultaneously.

I don't think it would be terribly difficult to create a mutex object 
and use it to work on the condvar implementation, but that would ignore 
the nice "synchronized" feature D has built-in.  I don't suppose there's 
currently any way to gain access to this hidden mutex object from within 
D code?


Sean
Feb 07 2004
parent Sam McCall <tunah.d tunah.net> writes:
Sean Kelly wrote:
 But the second 
 case is a bit trickier: "synchronized (Expression), where Expression 
 evaluates to an Object reference, allows only one thread at a time to 
 use that Object to execute the Statement."  Does this mean that the 
 object is held exclusively by the thread until execution passes out of 
 scope, or only that access is synchronized any time a thread attempts to 
 read or write the object within that block?
Looks like it's the same as in java, every object has a lock which can be taken by zero or one thread at a time. synchronized(obj) waits until the lock of the value of obj is free, takes it, executes the block, and releases it. Sam
Feb 07 2004