Acquiring Parent Mutex from Child Object

169 views Asked by At
#include <iostream>
#include <mutex>

using namespace std;

class A;
class B {
public:
  B(A *_parent = nullptr) {
    parent = _parent;
  }
  A *parent;
};

class A {
public:
  std::mutex m;
  B *b;
  A() {
    b = new B(this);
  }
};

int main() {
  A a_obj;
  B *b = new B(&a_obj);
  //b->parent->m.lock();
  return 0;
}

I believe the composed objects above function as expected and I've been using a similar design (my A creates B's and adds them to a data structure. The B's are constructed with references to their parent.)

When I tried to add threadsafe message-passing between A's and B's, the program crashed whenever a B tried to use a threadsafe container in A.

The code above recreates the problem. Why can B not acquire A's mutex?

0

There are 0 answers