Multithreading – why can’t signals / slots work with multiple threads?
•
Java
class A : public QObject{
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 tried to understand why B was not called_ slot(). Anyone can explain what happened and why B was not called_ slot()?
Solution
The problem is class A_ Ownership of timer members
Because you do not explicitly initialize it, it initializes without a parent object So a. movetothread (& athread) didn't move the timer to the thread, and then things became chaotic
Change the constructor of a to:
A() : _timer(this) {}
And your b_ Slot () will be called
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码