Using QMutex::tryLock and QMutexLocker

QMutexLocker clearly doesn't do quite what you need here, but you can write your own RAII wrapper easily enough:

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

and use it like so:

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
}

Note this locker is just sample code: a production version should probably be explicitly noncopyable.


Historical note: JBL's comment referred to a paragraph addressing a sentence no longer in the question. I'll paraphrase it as:

... something else could come along and lock the mutex

If it's possible, it will happen. If it's unlikely, it will happen only after you deploy it/scale it up/sell it to a customer.