문제

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?

도움이 되었습니까?

해결책

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_;
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top