使用QMutex :: tryLock和QMutexLocker

Add*_*ddy 5 c++ concurrency qt mutex

我有一个后台函数,目前有类似的东西:

void SomeClass::someFunction()
{
    if (!_mutex.tryLock())
    {
        // i want to know the mutex is locked, and then exit the function
        return;
    }
    else
    {
        _mutex.unlock();
    }

    QMutexLocker locker(_mutext);

    // do some stuff that **could** throw an exception
}
Run Code Online (Sandbox Code Playgroud)

我的困境涉及到这个_mutex.unlock()QMutextLocker声明.

如果_mutex被锁定,那么我想知道它.如果不是,那么我想锁定它.问题是我想用来QMutexLocker锁定_mutex大部分功能.该函数可能会抛出异常,因此手动解锁_mutex可能很困难并且容易出错.

上面的解决方案有效,但我担心的是,在其他东西_mutex.unlock()的减速之间的某个时刻QMutexLocker可能会出现并锁定互斥锁.

有没有人有更好的方法来做这个的建议?

谢谢.

Use*_*ess 6

QMutexLocker显然不能满足您的需求,但您可以轻松编写自己的RAII包装器:

class MutexTryLocker {
  QMutex &m_;
  bool locked_;
public:
  MutexTryLocker(QMutex &m) : m_(m), locked_(m.tryLock()) {}
  ~MutexTryLocker() { if (locked_) m_.unlock(); }
  bool isLocked() const { return locked_; }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

void SomeClass::someFunction() {
    MutexTryLocked locker(_mutex);

    if (!locker.isLocked()) {
        // we didn't get the lock, so return
        return;
    }

    // do some stuff that **could** throw an exception
}
Run Code Online (Sandbox Code Playgroud)

请注意,此锁定器只是示例代码:生产版本应该是显式不可复制的.


历史记录:JBL的评论提到了一个不再在问题中处理句子的段落.我会把它解释为:

......还有其他东西可以出现并锁定互斥锁

如果有可能,它就会发生.如果不太可能,只有在您将其部署/扩展/出售给客户才会发生.