Estoy tratando de implementar el trabajo en subprocesos para el cálculo paralelo. El problema que encontré es que quit()
ranura de thread
no se activa, por lo tanto las aplicaciones esperan en while(thread->isRunning())
. Es posible parar thread
de worker
¿Usando conexión de ranura de señal entre ellos? Aquí está mi código:
main.cpp:
#include <QCoreApplication>
#include "workermanager.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
WorkerManager workerManager;
workerManager.process();
return a.exec();
}
trabajador.h:
#include <QObject>
#include <QDebug>
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0) :
QObject(parent){}
signals:
void processingFinished();
public slots:
void process()
{
qDebug() << "processing";
emit this->processingFinished();
}
};
workermanager.h:
#include "worker.h"
#include <QThread>
class WorkerManager : public QObject
{
Q_OBJECT
public:
explicit WorkerManager(QObject *parent = 0) :
QObject(parent){}
void process()
{
QThread* thread = new QThread;
Worker* worker = new Worker;
connect(thread,SIGNAL(started()),worker,SLOT(process()));
connect(worker,SIGNAL(processingFinished()),thread,SLOT(quit()));
worker->moveToThread(thread);
thread->start();
qDebug() << "thread started";
while(thread->isRunning())
{
}
qDebug() << "thread finished";
//further operations - e.g. data collection from workers etc.
}
};
Respuestas
0 para la respuesta № 1Ese bucle mientras bloquea su hilo y le impide procesar cualquier señal, si realmente desea esperar a que finalice el hilo, debe iniciar un ciclo de eventos.
Pruebe esto en su lugar:
void process()
{
QThread* thread = new QThread;
Worker* worker = new Worker;
connect(thread,SIGNAL(started()),worker,SLOT(process()));
connect(worker,SIGNAL(processingFinished()),thread,SLOT(quit()));
worker->moveToThread(thread);
QEventLoop loop;
connect(thread, &QThread::finished, &loop, &QEventLoop::quit);
qDebug() << "thread started";
thread->start();
loop.exec();
qDebug() << "thread finished";
//further operations - e.g. data collection from workers etc.
}
Pero debo admitir que realmente no veo el punto.de este código. Si necesita esperar a que la tarea termine para seguir haciendo las cosas, también puede ejecutarla directamente. Por lo menos, su programa podrá procesar otras cosas (si las hay) mientras tanto.