在QT中提供了一个QThread类,一般程序是从main函数开始的二QThread是从run函数开始的执行的。
要创建一个线程就需要子类化QThread并重新实现run函数。
例如:
#ifndef THREAD_H
#define THREAD_H
#include<QThread>
class mythread : public QThread
{
Q_OBJECT
public:
mythread();
void closethread();
protected:
void run();//多线程执行的内容将通过重新该虚函数实现
bool isExist=false;
signals:
void over();
public slots:
};
#endif // THREAD_H
我们只需要重新实现run函数然后在其他位置调用start()函数即可启动线程。。。。start函数默认调用run函数,当run函数返回整个线程以便结束了,
线程的开始,结束,终止会发射started(),finished(),terminated(),等信号。。
我们可以使用isFinished,isRunning来查询线程的状态。可以使用wait()函数来阻塞直到线程的结束。
对于如何安全的结束线程,我们一般的操作就是在run函数函数中加上一个标志变量来控制线程的结束。
例如:
void mythread::closethread()
{
this->isExist=true;
}
void mythread::run()
{
while(1)
{
if(this->isExist)
{
this->isExist=false;
break;
}
qDebug()<<"线程运行中";
}
qDebug()<<"线程安全退出";
}
run函数中通过改变isExist变量来结束线程的运行。