简介
在开发过程中,使用线程是经常会遇到的场景,本篇文章就来整理一下 Qt 中使用线程的五种方式,方便后期回顾。前面两种比较简单,一笔带过了,主要介绍后面三种。最后两种方法博主最喜欢,不需要继承类,可以直接把需要执行的函数放到线程中去运行
1. 继承 QThread 重写 run 函数
class Thread : public QThread
{
Q_OBJECT
public:
virtual void run() override;
}
void Thread::run()
{
...
}
- 可调用 thread.start()启动线程,会自动调用 run 函数
- 可调用 thread.isRunning()判断线程是否已启动
- 可调用 thread.terminate()终止线程
- 可调用 thread.wait()等待线程终止
2. 继承 QObject 调用 moveToThread
class Test : public QObject
{
Q_OBJECT
public:
void test();
}
QThread th;
Test test;
test.moveToThread(&th);
需要注意的是:此方法与继承 QThread 相比较,继承 QThread 只有 run 函数中的操作是在线程中执行的,而此方法中所有的成员函数都是在线程中执行
3. 继承 QRunnable 重新 run 函数,结合 QThreadPool 实现线程池
#include <QObject>
#include <QRunnable>
#include <QThread>
#include <QThreadPool>
#include <QDebug>
class BPrint : public QRunnable
{
void run()
{
for ( int count = 0; count < 5; ++count )
{
q