Minimize lock time

Steven Schveighoffer schveiguy at yahoo.com
Mon Jun 14 05:19:39 PDT 2010


On Thu, 10 Jun 2010 02:54:37 -0400, Kagamin <spam at here.lot> wrote:

> Let's consider the following code:
>
> synchronized(syncRoot)
> {
>   if(condition)opSuccess();
>   else writeln(possibly,slow);
> }
>
> Suppose the else close doesn't need to be executed in lock domain and  
> can be slow. How to minimize lock time here?
>
> synchronized(syncRoot)
> {
>   if(condition)opSuccess();
>   else goto Lwrite;
> }
> Lwrite: writeln(possibly,slow);
>
> We can do this... but...

What about using a Mutex object?

mut.lock();
if(condition)
{
    scope(exit) mut.unlock();
    opSuccess();
}
else
{
    mut.unlock();
    writeln(possibly, slow);
}

I think it's in core.sync or something like that.  Mutex can even take  
over the standard monitor element of another object, so for instance you  
could assign it as the monitor of your syncRoot, so your other code that  
uses syncRoot and synchronized still works.

-Steve


More information about the Digitalmars-d-learn mailing list