MultiThread QObject Treated as Nullptr
-
I'm having an issue with Qt threads and passing/maintaining QObject references (all classes are Q_Objects).
The Gui class has an initWorker() function which initializes some objects, one of which(ObjA)is passed into another object's init function (ObjB(ObjA*)). When using theObjAinside theObjBfor connecting slots and signals, it fails and throws an error in the console sayingObjAis anullptr. However, it shouldn't be anullptrsince it was initialized and I am able to make function calls on the instance ofObjAthat was passed in and it works just fine. I'm not quite sure what the issue is here, I'm pretty sure I'm breaking some threading rule here but I'm not exactly sure what it is.I've found I can get around the issue by having
ObjBinitialized insideObjAbut I lose the convenient reference toObjBin the Gui class.Here's a general code outline of what I'm doing. Any help would be appreciated.
class GuiClass; // Target Thread: GUI class ObjA; // Target Thread: Worker class ObjB; // Target Thread: Worker class ObjC: // Target Thread: Worker/* Main.cpp */ QApplication a(argc, argv); GuiClass gui; a.exec();/* GuiClass */ QThread _workerThread; ObjA* _objA; ObjB* _objB; GuiClass::GuiClass(QWidget *parent) : QMainWindow(parent), ui (new Ui::GuiClass) { initWorkers(); } initWorkers() { _objA = new ObjA(); _objB = new ObjB(_objA); // Needs reference to ObjA instance - done in same thread /* Move both objects to worker thread */ _objA.moveToThread(_workerThread); _objB.moveToThread(_workerThread); /* Connect thread start to initializtion function */ connect(_workerThread, SIGNAL(started()), _objB, SLOT(init())); _workerThread.start(); }/* ObjB Class */ ObjA* _objA; ObjC* _objC; ObjB::ObjB(QObject *parent, ObjA* objA) : QObject(parent) { _objA = objA; // Debugger shows objA as `nullptr` here for some reason } void ObjB::init() { _objC = new ObjC(); /* Connect Object C signal to Object A slot */ connect(_objC, SIGNAL(sigFoo()), _objA, SLOT(slotFoo)); // Error output to console _objA->doThing(); // Works just fine /* This connect throws error in the console (no segfault) saying _objA is nullptr and it cannot * connect the slot to the signal. * * When using QT debugger _objA value = 0x0 (nullptr) which reinforces the error is correct * however, calling the _objA to perform some work or return a value, works just fine. */ }