mercredi 27 juillet 2016

Conditional use of std::lock_guard

I have a function where the statement foo should be executed under lock_guard but only when a pointer to a mutex object has been provided to the function as a parameter. Otherwise foo does not have to be protected by lock_guard.

I cannot use the lock_guard within an if because the lock will be released immediately when the if block ends.

so, this code is nonsense:

bar( std::mutex * optionalMutex = nullptr )
{
   ...
   if ( nullptr != optionalMutex ) {
      std::lock_guard<std::mutex> lockScope( *optionalMutex );
   }          <- Here the lock ends

   foo...     <- foo is not protected when optionalMutex was provided
}

I tried something like this:

bar( std::mutex * optionalMutex = nullptr )
{
   ...
   nullptr == optionalMutex ? 0 : std::lock_guard<std::mutex> lockScope( *optionalMutex );

   // this scope should be protected by lock_guard when optionalMutex was provided

   foo...
}

More or less, the only one possible solution for me is to repeat foo:

bar( std::mutex * optionalMutex = nullptr )
{
   ...
   if ( nullptr != optionalMutex ) {
      std::lock_guard<std::mutex> lockScope( *optionalMutex );
      foo...
   }  else {
      foo...
   }
}

The compiler gcc 4.9.3 does not compile the 2nd example and complains: error: expected primary-expression before 'lockScope'

But I do want to avoid any code duplicates and therefore also the duplicate foo.

My question:

Is there an elegant way how to implement this problem and not to use duplicate foo. I know, I could use a lambda function but I am curious if there is an another solution.

Aucun commentaire:

Enregistrer un commentaire