问题
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?
回答1:
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_;
};
来源:https://stackoverflow.com/questions/10752280/check-optional-mutex-before-scoped-locking