Qt提供了三种实现多线程的方式:
1)继承QThread,重写run方法
代码如下:
MyThread::MyThread(QObject *parent)
:QThread(parent){
}
void MyThread::run()
{
QTimer *timer = new QTimer();
connect(timer,&QTimer::timeout,this,[](){
qDebug() << "TMyThreadID:::" << QThread::currentThreadId();
});
timer->start(1000);
this->exec();//注意:必须调用exec才会进入事件循环
}
2)moveToThread(官方推荐)
代码如下:
class Test : public QObject
{
Q_OBJECT
public:
Test(QObject *parent = nullptr):QObject(parent){}
~Test(){}
void test(){qDebug() << "testThreadID" << QThread::currentThreadId();}
};
void MyThread()
{
QThread *thread = new QThread(this);
Test *testObj = new Test();
testObj->moveToThread(thread);
QPushButton *pBtn = new QPushButton(this);
connect(pBtn,&QPushButton::clicked,testObj,&Test::test);
qDebug() << "mainThreadID" << QThread::currentThreadId();
thread->start();
}
3)QtConcurrent::run方法(临时线程)
QtConcurrent::run([=]()
{
qDebug() << "QtConcurrentID" << QThread::currentThreadId();
});
4)信号和槽函数执行线程说明
a.如果信号和槽在同一个线程,槽在发送信号所在线程执行
b.如果信号和槽在不同线程,且connect第五个参数为Qt::DirectConnection,槽在发送信号所在线程中执行
c.如果信号和槽在不同线程,且connect第五个参数为Qt::QueuedConnection,槽在接受所在线程中执行