Search code examples
multithreadingqtsignals-slotsqthread

why signal/slot not working with multiple threads?


class A : public QObject{

  Q_OBJECT

signals:
  void a_sig();

public:
  A(){ }

public slots:
  void begin(){
    QObject::connect(&_timer, SIGNAL(timeout()), this, SIGNAL(a_sig()));
    _timer.start(1000); 
  }

private:
  QTimer _timer;
};


class B : public QObject{

  Q_OBJECT

public:
  B(){ value = 0; }

public slots:
  void b_slot(){

    ++value;
    QFile file("out.txt");
    file.open(QIODevice::WriteOnly);
    QTextStream out(&file);
    out << value << "\n";
    file.close();
  }

private:
  int value;
};

int main(int argc, char **argv){

  QCoreApplication app(argc, argv);

  A a;
  B b;
  QThread aThread;
  QThread bThread;

  QObject::connect(&aThread, SIGNAL(started()), &a, SLOT(begin()));
  QObject::connect(&a, SIGNAL(a_sig()), &b, SLOT(b_slot()));

  a.moveToThread(&aThread);
  b.moveToThread(&bThread);

  aThread.start();
  bThread.start();

  return app.exec();
}

I'm trying to understand why b_slot() isn't getting called. Can anyone explain what's happening, and why b_slot() isn't getting called?


Solution

  • The problem is the ownership of the _timer member of the A class.

    Since you're not explicitly initializing it, it is initialized without a parent object. So the a.moveToThread(&aThread) isn't moving the timer to aThread, and things get confused after that.

    Change A's constructor to:

    A() : _timer(this) {}
    

    and your b_slot() will get called.