转自:https://blog.csdn.net/hanzhaoqiao1436/article/details/80957945
在编程当中遇到了一些问题:到底该使用哪种方式去创建线程呢?
Qt创建线程有两种方式。第一种继承QThread重写run函数,需要注意的是只有run函数才在线程中执行,其它函数被父类直接调用时,它执行所在的线程还是在父类所在的线程中。第二种继承QObject使用moveToThread启动线程,这也是官方推荐的写法,比较灵活通用。
第一种 继承QThread
class ThreadTest: public QThread
{
public:
ThreadTest(QObject* parent = nullptr);
void doWork();
protected:
void run();
};
void ThreadTest::doWork()
{
QString msg = QString("%1 -> %2 threadid:[%3]")
.arg(__FILE__)
.arg(__FUNCTION__)
.arg((int)currentThreadId());
qDebug() << msg;
}
void ThreadTest::run()
{
QString msg = QString("%1 -> %2 threadid:[%3]")
.arg(__FILE__)
.arg(__FUNCTION__)
.arg((int)currentThreadId());
qDebug() << msg;
doWork();
for(int i=0;i<3;i++)
{
qDebug() << "doWork:" << i;
sleep(1);
}
}
主函数调用,这里也打印输出了主函数的线程ID,又主动去调用了ThreadTest中的doWork函数
qDebug() << "MainThreadid: " << (int)QThread::currentThreadId();
m_pThreadTest = new ThreadTest(this);
connect(m_pThreadTest,&ThreadTest::finished,m_pThreadTest,&ThreadTest::deleteLater);
connect(m_pThreadTest,&ThreadTest::finished,this,&Widget::threadFinished);
m_pThreadTest->doWork();
m_pThreadTest->start();
输出结果如下
结果证明只有run函数里面才在线程中执行。
第二种 继承QObject,使用moveToThread
class MoveToThreadTest : public QObject
{
public:
MoveToThreadTest();
public slots:
void doWork();
void start();
void stop();
private:
QMutex m_Mutex;
bool m_bRun;
};
MoveToThreadTest::MoveToThreadTest()
{
m_bRun = true;
}
void MoveToThreadTest::doWork()
{
QString msg = QString("%1 -> %2 threadid:[%3]")
.arg(__FILE__)
.arg(__FUNCTION__)
.arg((int)QThread::currentThreadId());
qDebug() << msg;
}
void MoveToThreadTest::start()
{
QString msg = QString("%1 -> %2 threadid:[%3]")
.arg(__FILE__)
.arg(__FUNCTION__)
.arg((int)QThread::currentThreadId());
qDebug() << msg;
doWork();
for(;;)
{
QThread::sleep(1);
qDebug() << "isRuning ";
{
QMutexLocker locker(&m_Mutex);
if(m_bRun == false)
break;
}
}
}
void MoveToThreadTest::stop()
{
QString msg = QString("%1 -> %2 threadid:[%3]")
.arg(__FILE__)
.arg(__FUNCTION__)
.arg((int)QThread::currentThreadId());
qDebug() << msg;
QMutexLocker locker(&m_Mutex);
m_bRun = false;
}
主函数调用,连接了deleteLater让线程退出时自杀,尽量避免手动调用delete去删除对象,因为它不安全
qDebug() << "MainThreadid: " << (int)QThread::currentThreadId();
m_pMoveThread = new MoveToThreadTest();
m_pMoveThread->moveToThread(&m_Thread);
connect(&m_Thread,&QThread::started,m_pMoveThread,&MoveToThreadTest::start);
connect(&m_Thread,&QThread::finished,m_pMoveThread,&MoveToThreadTest::deleteLater);
connect(&m_Thread,&QThread::finished,this,&Widget::threadFinished);
m_pMoveThread->doWork();
m_Thread.start();
优雅的终结掉线程
void Widget::on_pushButton_clicked()
{
if(m_pMoveThread)
{
m_pMoveThread->stop();
m_Thread.quit();
m_Thread.wait();
}
}
根据线程ID我们得出,连接started信号的槽函数才是归属于线程。
总结
线程的创建推荐使用moveToThread的方法,结束线程推荐使用变量+互斥量的形式控制退出,同时连接deleteLater让线程自杀,尽量避免terminate这种强制性的退出,最好也不要手动delete对象。
转自:https://blog.csdn.net/hanzhaoqiao1436/article/details/80957945
QMutexLocker如何安全锁住全局变量:https://blog.csdn.net/zhaoyuaiweide/article/details/77991658