为什么信号/槽不能用于多线程?
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();
}
我试图理解为什么 b_slot()
没有被调用。谁能解释一下发生了什么,以及为什么 b_slot()
没有被调用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于
A
类的_timer
成员的所有权。由于您没有显式初始化它,因此它是在没有父对象的情况下进行初始化的。因此,
a.moveToThread(&aThread)
并未将计时器移至aThread
,之后事情就会变得混乱。将
A
的构造函数更改为:并且您的
b_slot()
将被调用。The problem is the ownership of the
_timer
member of theA
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 toaThread
, and things get confused after that.Change
A
's constructor to:and your
b_slot()
will get called.问题是,当对象
a
移动到aThread
时,_timer
对象仍然属于原始主线程。尝试在begin
方法中初始化_timer
,如下所示:The problem is that while object
a
is moved toaThread
,_timer
object still belongs to the original main thread. Try initializing_timer
insidebegin
method like that: