Qt中使用多线程常用的方式有2种
1. 继承QThread重写run函数
线程在执行过程中是不能释放线程对象的可以使用
QThread *thread = new QThread(this);
connect(thread, SIGNAL(finished()),thread ,SLOT(deleteLater()));
注意这2句代码是在主线程中执行的线程对象属于主线程,deleteLater由主线程执行,如果在子线程中创建线程对象属于子线程要考虑子线程是否还能触发信号执行槽函数
有父对象的话,父对象释放时,会来释放该子对象
class CThread : public QThread
{
public:
CThread(QObject* parent = nullptr);
~CThread();
//线程执行完毕后,运行该函数 与QThread::finished信号连接
void threadFinish();
protected:
//重写run函数 子线程会执行该函数类的代码
void run();
};
CThread::CThread(QObject* parent) : QThread(parent)
{
qDebug() << "cthread cthread";
//执行完毕后执行ThreadFinish
connect(this, &CThread::finished, this, &CThread::threadFinish);
}
CThread::~CThread()
{
qDebug() << "cthread ~cthread";
}
//我们这里重写了run函数且没有调用 QThread::exec() 函数(消息循环)子线程收到信号执行槽函数依赖消息循环 所以该线程不能收到信号执行槽函数
//打印内容后就会触发finished信号 表示线程执行完毕
void CThread::run()
{
qDebug() << "cthread run threadId: " << QThread::currentThreadId();
}
void CThread::threadFinish()
{
qDebug() << "cthread finish";
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CMainWindow w;
w.show();
CThread* pThread = new CThread();
//connect只是一个静态方法
//线程执行完毕后释放pThread对象
QObject::connect(pThread, &CThread::finished, pThread, &CThread::deleteLater);
//启动线程
pThread->start();
return a.exec();
}
输出:
main thread id: 0x1dd8
cthread cthread
cthread run threadId: 0x24e0
cthread finish
cthread ~cthread