2

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?

Community
  • 1
  • 1
TSG
  • 4,242
  • 9
  • 61
  • 121
  • 1
    Mutex is associated with protected resource, and not class that accesses this resource. So, in your simple case, when resource is global variable, mutex should be global variable as well. – Alex F Oct 03 '13 at 06:15
  • The OS doesn't know anything about resources being protected. A mutex created on the stack not shared with the other threads won't protect anything. All threads accessing globalvar must share the same mutex instance. Thus the mutex should be in the same scope as the data to protect. – Frank Osterfeld Oct 03 '13 at 07:46

1 Answers1

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?

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.

László Papp
  • 51,870
  • 39
  • 111
  • 135