qtqtcoreqmutex

QMutex - does this mean I need a global mutex variable


I need to implement a mutex that works 2 ways: 1. protect a resource from across multiple classes, and 2. protect a resources from a method in a class that is a slot and may be re-entrant. For example (pseudo C++):

Class A {
  function aaa() {
    QMutex mutex;
    mutex.lock();
    globalvar++;
    mutex.unlock()
  }
}

Class B {
  function bbb() {
    QMutex mutex;
    mutex.lock();
    globalvar++;
    mutex.unlock()
  }
}
  1. I read this posting which says that the scenario 2 is covered since A.aaa being interrupted by A.aaa is handled (somehow Qt/OS knows it is the same resource being protected. Right?

  2. As for A.aaa and B.bbb protecting the same resource I think it won't work, since Qt/OS doesn't know its the same resource / mutex? Does that mean the variable mutex needs to be a global so that multiple unrelated classes can safely access it?


Solution

  • I read this posting which says that the scenario 2 is covered since A.aaa being interrupted by A.aaa is handled (somehow Qt/OS knows it is the same resource being protected. Right?

    Yes, although it seems you should use QMutexLocker in such cases when the locking is tied to a scope to avoid the mistakes of forgetting the unlock. This is called RAII in C++.

    Strictly speaking, it is QMutex that is responsible for locking the resource.

    As for A.aaa and B.bbb protecting the same resource I think it won't work, since Qt/OS doesn't know its the same resource / mutex? Does that mean the variable mutex needs to be a global so that multiple unrelated classes can safely access it?

    It is a rare scenario, but yes. Although you may want to wrap the global variable into a type, like a custom struct.