我想在Qt中从我用QtConcurrent::run调用的函数中发出一个信号
这个是可能的吗?我的位置好像从来没人叫过我。所有的信号、槽和函数都是同一个类对象的一部分。我已经尝试在主线程和从线程中建立连接。我真的不关心信号和插槽是否在同一个线程中,我只想让它发生。
谢谢
发布于 2016-12-13 05:42:00
下面的代码在Qt 4.8.7中运行得很好。该信号从工作线程发出,并在主线程中使用。我们断言槽在主线程中运行,而functor在辅助线程中运行。
// https://github.com/KubaO/stackoverflown/tree/master/questions/concurrent-emit-qt4-7114421
#include <QtCore>
class Helper : public QObject {
Q_OBJECT
public:
int n = 0;
Q_SLOT void increment() {
Q_ASSERT(QThread::currentThread() == qApp->thread());
n++;
}
};
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
Helper helper;
Q_ASSERT(helper.n == 0);
QtConcurrent::run([&]{
Q_ASSERT(QThread::currentThread() != qApp->thread());
QObject src;
QObject::connect(&src, SIGNAL(destroyed(QObject*)), &helper, SLOT(increment()));
QObject::connect(&src, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
});
app.exec();
Q_ASSERT(helper.n == 1);
}
#include "main.moc"在Qt 5中,您不需要helper类来演示它的工作方式:
#include <QtConcurrent>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
int n = 0;
Q_ASSERT(n == 0);
QtConcurrent::run([&]{
Q_ASSERT(QThread::currentThread() != qApp->thread());
QObject src;
QObject::connect(&src, &QObject::destroyed, &app, [&]{
Q_ASSERT(QThread::currentThread() == qApp->thread());
n ++;
qApp->quit();
});
});
app.exec();
Q_ASSERT(n == 1);
}发布于 2011-08-19 07:28:01
您可以对该连接使用Qt::QueuedConnection (将其传递给建立连接的connect调用),因为信号将始终从不同于接收器对象线程的线程发出。
Qt::AutoConnection也会做同样的事情,并将信号添加到接收对象的线程的事件队列中。
如果接收线程被阻塞,因此永远不会重新进入事件队列,则接收对象的槽不能接收信号。
发布于 2011-08-19 19:46:15
你真的应该在QtConcurrent::run()中使用QFuture和QFutureWatcher。
https://stackoverflow.com/questions/7114421
复制相似问题