Boost logo

Boost :

From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2001-07-21 09:04:54


> void foo ( )
> {
> boost::mutex::lock ( MyMutex );
>
> // do some stuff
>
> lock.unlock ( ); // fine
>
> // some more stuff
>
> lock.lock ( ); // looks very strange - somewhat ctor like?
> // ...
> }

IMHO..

void foo ( )
{
   { // do some synchronized stuff

     synch_region_guard srg( mtxLock );

     //...

     srg.attach_cleanup_handler( this_region_cleanup_handler,.... );

     while ( !.... ) // cancelable wait
       cndSomeState.wait( mtxLock );

     //...
     //srg.detach_cleanup_handle();
     //...

   }

   // do some more non-synchronized stuff
   //...

   { // try do some synchronized stuff

     synch_region_guard srg( semLock,TRY );

     if ( srg.access_granted () ) {
       //...
       if ( .... ) {
         // keep semaphore locked
         srg.disable_cleanup();
       }
     }
     else {
       //...
     }

   }

   { // try do some synchronized stuff with synch. timeout

     synch_region_guard srg( rwlock,timeout,READ_LOCK );

     if ( srg.access_granted() ) {
       //...
     }
     else {
       //...
     }

   }

}

synch_region_guard basically does three things:

1) marks the begin of synch. region -- performs
   try/timed/infinite synch. via specified synch
   object and specified synch operation (with
   timeout for timed synch);
2) keeps track of optional synch region cleanup handler;
3) on synch region exit performs required cleanup; note that
   an optional cleanup handler could enforce early "unlock"
   in order to do some heavy stuff (e.g. cnd.broadcast) w/o
   synchronization in place while doing these final operations.

regards,
alexander.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk