c++multithreadingmutexcritical-sectionscoped-lock

Check optional mutex before scoped locking


I have a constructor that optionally allows the user to pass a ponter to a Boost mutex. If no mutex is supplied, the member pointer pMyMutex is set to NULL. This gives the user the option of applying some thread safety if they wish. However, I cannot use a scoped_lock with this kind of check for obvious reasons :)

if (pMyMutex != NULL)
    const boost::mutex::scoped_lock l(*pMyMutex);

//The lock is already out of scope
processStuff(x, y, z);

Can anyone suggest a neat and simple solution to such a requirement?


Solution

  • Implement your own wrapper similar with scoped_lock to hide the decision inside it: wrapping a pointer to a mutex and checking if the pointer is null (no locking applied) or not null (locking applied). Some skeleton:

    class ScopedLockEx
    {
    public:
        ScopedLockEx( boost::mutex* pMutex)
           : pMutex_( pMutex)
        {
           if( pMutex_) pMutex_->lock();
        }
    
        ~ScopedLockEx()
        {
           if( pMutex_) pMutex_->unlock();
        }
    private:
        boost::mutex* pMutex_;
    };