Multithreading QT线程从不运行
我正在尝试使用Qthread,但似乎无法确定线程实际执行的时间。我只能在创建线程的函数退出时看到它的执行,但我不希望当前函数在一次执行后退出。我想在这个函数的循环中多次运行线程 //////////////////////////////////////////////////////////////////////Multithreading QT线程从不运行,multithreading,qt,Multithreading,Qt,我正在尝试使用Qthread,但似乎无法确定线程实际执行的时间。我只能在创建线程的函数退出时看到它的执行,但我不希望当前函数在一次执行后退出。我想在这个函数的循环中多次运行线程 ////////////////////////////////////////////////////////////////////// // --- PROCESS --- // Start processing data. void GrayDisplay::process() { std::cout
// --- PROCESS ---
// Start processing data.
void GrayDisplay::process()
{
std::cout << "Thread context!" << std::endl; //I never see this print
emit finished();
}
void gig::OnPlay()
{
//Create thread and assign selected
QThread* thread = new QThread;
if(ui->colorBox->currentIndex() == 0 )
{
GrayDisplay* display = new GrayDisplay();
display->moveToThread(thread);
connect(display, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), display, SLOT(process()));
connect(display, SIGNAL(finished()), thread, SLOT(quit()));
connect(display, SIGNAL(finished()), display, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
std::cout << "Creating Thread!" << std::endl;
}
else
{
cout << "\nInvalid mode selected";
return;
}
pSemaphore->acquire();
run = true;
pSemaphore->release();
//Read data
while(run) //set false by click event
{
QCoreApplication::processEvents();
Sleep(33);
if (thread->isRunning()) //Always prints and I expect just the first loop iteration to print, not infinitely as it does
cout << "Worker is-STILL-Running\n";
thread->start();
QApplication::exec();
QCoreApplication::processEvents();
// while (!thread->isFinished())
// {
// QApplication::exec();
// QCoreApplication::processEvents();
// } //Never returns
} //WHILE RUN LOOP
return;
}
我在这里看到过类似的线程,但解决方案似乎总是:
QCoreApplication::processEvents;
这似乎对我没有帮助。如果我创建并启动线程,它似乎总是在运行,但从来没有做过任何事情从未看到我的打印语句,也从未完成。我添加了sleep来模拟每个循环在开始新线程之前完成所需的时间。我希望到那时前一个线程已经完成。我试图让一个简单的版本正常工作,但无法找出我遗漏了什么。我只想在离开OnPlay函数时删除该线程,但执行该线程多次,直到我决定退出。我认为您在以下线程中遇到了与我相同的问题: 问题是线程的事件循环只有在进程返回后才建立。这意味着在此之前发送到线程的所有退出事件都将被删除 qeventloop.cpp:
// remove posted quit events when entering a new event loop
QCoreApplication *app = QCoreApplication::instance();
if (app && app->thread() == thread())
QCoreApplication::removePostedEvents(app, QEvent::Quit);
在我的例子中,一个简单的
QThread::currentThread()->quit();
在流程结束时,我们做到了这一点。为什么要使用QApplication::exec;在那里?没有循环,因为QApplication::exec;永远不会结束。只是有人在我搜索的众多论坛中的一个上建议的,所以我想我会试试。看起来这可能就是问题所在。过了一段时间我才开始尝试任何东西,这似乎是个问题。谢谢,我错了,那不是问题所在。我仍然看到线程永远在运行,但从来没有真正做任何事情或完成。我曾尝试显式调用display->process,但在删除QApplication::exec时忘记删除它;当我尝试使用thread->start时,我的线程仍然没有用。只有显式调用进程似乎有效,但这并不是一个真正的新线程。