Check optional mutex before scoped locking

老子叫甜甜 提交于 2019-12-24 10:56:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!