在作用域锁定之前检查可选的互斥锁 [英] Check optional mutex before scoped locking

查看:104
本文介绍了在作用域锁定之前检查可选的互斥锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个构造函数,可以选择允许用户将ponter传递给Boost互斥体.如果没有提供互斥锁,则成员指针pMyMutex设置为NULL.用户可以根据需要选择应用一些线程安全性.但是,出于明显的原因,我不能在这种检查中使用scoped_lock:

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?

推荐答案

使用类似于scoped_lock的包装器将其隐藏在其中:将指针包装到互斥体并检查该指针是否为null(未应用锁定)或不为null(已应用锁定).一些骨架:

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_;
};

这篇关于在作用域锁定之前检查可选的互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆