我无法正确关闭运行两个设备通信线程的QT应用程序。
代码通常在Windows上按预期工作,但在OS X / clang下,应用程序有时会报告关闭或不关闭段错误,即使完全关闭也不会清除共享内存,这意味着用户无法重新打开在没有重新启动计算机的情况下关闭应用程序。我应该提一下,我从其他一些开发人员那里继承了所有这些代码,我知道大多数代码都没有遵循典型的最佳实践(我试图解决这个问题)。
在QMainWindow派生类构造函数中:
LFK::LFK(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::LFK)
{
//...
connect(this, SIGNAL(StartWorkerSignal()), &bleWorker, SLOT(RunSlot()));
bleWorkerThread.start();
bleWorker.moveToThread(&bleWorkerThread);
bleWorkerThread.setPriority(QThread::HighestPriority);
connect(this, SIGNAL(StartWorkerSignal()), &hidWorker, SLOT(RunSlot()));
hidWorkerThread.start();
hidWorker.moveToThread(&hidWorkerThread);
hidWorkerThread.setPriority(QThread::HighestPriority);
emit(StartWorkerSignal());
}
LFK::~LFK()
{
qDebug() << "Asking threads to exit";
emit(ThreadStopSignal());
bleWorkerThread.terminate();
hidWorkerThread.terminate();
qDebug() << "Waiting for HID";
hidWorkerThread.wait();
qDebug() << "Waiting for BLE";
bleWorkerThread.wait();
qDebug() << "deleting ui";
delete ui;
qDebug() << "done";
exit(0);
}
主:
QSharedMemory mem(SHARED_MEM_KEY);
/*try to allocate some arbitrary memory in our shared area,
if this fails we know the shared area was not created*/
if(!mem.create(8))
{
QMessageBox::warning(NULL, "Error", projectstrings::alreadyRunningMsg);
a.exit(0);
return 0;
}
LFK w;
最后,在每个帖子中:
BleWorker::BleWorker(QObject *parent) :
QThread(parent)
{
//...
allowRun = TRUE;
}
void BleWorker::RunSlot()
{
while(allowRun)
{
QCoreApplication::processEvents();
//do communication stuff
}
}
void BleWorker::ThreadStopSlot()
{
allowRun = false;
qDebug() << "Ending BLE WORKER";
}
当我尝试通过将allowRun
设置为false来结束线程时,调试显示它刚刚从while循环结束时掉落,然后应用程序挂起WorkerThread.wait();
个调用,从不关闭
使用terminate似乎是让应用程序始终关闭的唯一方法,但我知道这是一种糟糕的做法。