嗨,我正在尝试在Qt的控制台应用程序中创建线程。
我的主要方法是:
#include<featurematcher.h>
#include<QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
FeatureMatcher * fm = new FeatureMatcher();
fm->start();
return a.exec();
}
我的FeatureMatches类如下:
#ifndef FEATUREMATCHER_H
#define FEATUREMATCHER_H
#include<QThread>
class FeatureMatcher:public QThread
{
Q_OBJECT
public:
FeatureMatcher();
void run();
};
#endif // FEATUREMATCHER_H
和cpp文件:
#include "featurematcher.h"
#include <iostream>
FeatureMatcher::FeatureMatcher()
{
}
void FeatureMatcher::run()
{
std::cout<<"Process"<<std::endl;
}
我的问题是,当我开始运行程序时,它只调用一次run方法。我期望输出的输出是无限数量的“进程”,但只能输出一次。
我在哪里失踪?
最佳答案
首先,它通常是not a good idea to inherit QThread
。但是,如果绝对必须这样做,则必须自己实现循环。您可以通过两种方式来实现。
您可以创建一个QTimer
,然后运行QThread::exec
:
void FeatureMatcher::run()
{
this->moveToThread(this);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(onTimer()));
timer->setInterval(1000);
timer->start();
exec();
}
或者您可以创建一个无限循环:
void FeatureMatcher::run()
{
while (1) {
std::cout<<"Process"<<std::endl;
}
}
更新了第一个示例2。
关于c++ - Qthread调用仅运行一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30398351/