首先,您可以跨 QThreads 使用信号和槽,甚至可以使用Qt::BlockingQueuedConnection 等待槽执行。见Qt documentation。
但是,这要求目标 QObject 存在于具有正在运行的事件循环的线程中。在您的情况下,由于您已重载 QThread::run(),您将不会有事件循环。
在我看来,您有 2 种方法来修复您的代码,要么进行小修复,要么更改设计并使用事件循环。
1。快速修复
void run()
{
QString cmd;
QProcess p;
connect(&p, SIGNAL(finished(int)), this, SLOT(quit()));
//connect(this, SIGNAL(signalTerminateProcess()), &p, SLOT(kill())); // queued connect that doesn't kill my process
p.start(cmd);
while(! p.waitForFinished(100)) //Wake up every 100ms and check if we must exit
{
if (QThread::currentThread()->isInterruptionRequested())
{
p.terminate();
if (! p.waitForFinished(1000))
p.kill()
break;
}
}
qInfo("process done");
}
int cleanUp()
{
thread->requestInterruption();
thread->wait();
}
或
QProcess *process = nullptr;
void run()
{
QString cmd;
QProcess p;
process = &p; //You shouldn't do that in real code
connect(&p, SIGNAL(finished(int)), this, SLOT(quit()));
//connect(this, SIGNAL(signalTerminateProcess()), &p, SLOT(kill())); // queued connect that doesn't kill my process
p.start(cmd);
while(! p.waitForFinished(100)) //Wake up every 100ms and check if we must exit
{
QCoreApplication::processEvents();
}
qInfo("process done");
process = nullptr;
}
int cleanUp()
{
QTimer::singleShot(0, process, &QProcess::terminate);
// Qt 5.10 -> QMetaObject::invokeMethod(process, &QProcess::terminate);
if (! thread->wait(1000))
{
QTimer::singleShot(0, process, &QProcess::kill);
thread->wait();
}
}
2。事件循环修复
// Create thread
QThread thread;
thread.start();
// Create process and move it to the other thread
QProcess process;
process.moveToThread(&thread);
void startProcess()
{
p.start(cmd);
}
QMutex mutex;
void stopProcess()
{
p.terminate();
if (!p.waitForFinished(1000))
p.kill();
p.moveToThread(qApp->thread());
mutex.unlock();
}
// Call startProcess() in the other thread
QTimer::singleShot(0, &process, &startProcess);
// Call stopProcess() in the other thread
mutex.lock();
QTimer::singleShot(0, &process, &stopProcess);
mutex.lock();
thread.quit();
if (!thread.wait(100))
thread.terminate();
你可以:
- 使用原子或使用与
Qt::BlockingQueuedConnection 连接的信号替换互斥锁。
- 将
startProcess() 和 stopProcess() 替换为插槽和 lambda。
- 将调用
QTimer::singleShot() 替换为QMetaObject::invokeMethod() 或使用信号。 请注意,您可以将Qt::BlockingQueuedConnection 与QMetaObject::invokeMethod() 一起使用