m_thread=new QThread;
m_objThread=new MyThread;
m_objThread->moveToThread(m_thread);
connect(ui->btn_add,&QPushButton::clicked,m_objThread,&MyThread::slot_add,Qt::DirectConnection);
m_thread->start();
主线程Id 0x3500
MyThread的线程Id 0x3500
m_thread=new QThread;
m_objThread=new MyThread;
m_objThread->moveToThread(m_thread);
connect(ui->btn_add,&QPushButton::clicked,m_objThread,&MyThread::slot_add,Qt::QueuedConnection);
m_thread->start();
主线程Id 0x344c
MyThread的线程Id 0x39d8
m_thread=new QThread;
m_objThread=new MyThread;
m_objThread->moveToThread(m_thread);
connect(ui->btn_add,&QPushButton::clicked,m_objThread,&MyThread::slot_add);
m_thread->start();
主线程Id 0xc90
MyThread的线程Id 0x3a08
结论:直接连接模式信号槽在同一线程内;队列连接模式和默认连接模式效果一样,在不同线程内
(是否在同一线程内部和信号槽的位置无关)
---------------------------------------------------------------------------------------------------------------------------------
m_thread=new QThread;
m_objThread=new MyThread;
connect(m_thread,&QThread::started,m_objThread,&MyThread::slot_add);
m_thread->start();
主线程Id 0x21d8
MyThread的线程Id 0x21d8
m_thread=new QThread;
m_objThread=new MyThread;
connect(m_thread,&QThread::started,m_objThread,&MyThread::slot_add,Qt::QueuedConnection);
m_thread->start();
主线程Id 0x3864
MyThread的线程Id 0x3864
m_thread=new QThread;
m_objThread=new MyThread;
connect(m_thread,&QThread::started,m_objThread,&MyThread::slot_add,Qt::DirectConnection);
m_thread->start();
主线程Id 0x7a0
MyThread的线程Id 0x2274
结论:如果使用started信号槽,可以省略movetothread,但是第五个参数必须是DirectConnection
(是否在同一线程内部和信号槽的位置无关)
总结:可以直接使用默认连接。如果不想写movetothread方法,那就使用started信号槽,但是要加上DirectConnection
---------------------------------------------------------------------------------------------------------------------------------
QtConcurrent的使用:
1.添加:QT+=concurrent
2.引入:#include <QtConcurrent>
3.使用:
1)使用lambda,QtConcurrent::run([=](){ ......});
2)调用外部函数(非成员函数),
qDebug()<<"主线程Id"<<QThread::currentThreadId();
QtConcurrent::run([=](){
qDebug()<<"QtConcurrent线程Id"<<QThread::currentThreadId();
});
主线程Id 0x3e6c
QtConcurrent线程Id 0x4608
void add(QString str,int a)
{
qDebug()<<"QtConcurrent线程Id"<<QThread::currentThreadId();
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug()<<"主线程Id"<<QThread::currentThreadId();
QFuture<void> f1 =QtConcurrent::run(add,QString("aaa"),int(1));
f1.waitForFinished();
}
主线程Id 0x3cfc
QtConcurrent线程Id 0x5030
3)调用成员函数
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug()<<"主线程Id"<<QThread::currentThreadId();
QFuture<void> f1 =QtConcurrent::run(this,&MainWindow::fun1,QString("aaa"),int(1));
f1.waitForFinished();
}
void MainWindow::fun1(QString str,int number)
{
qDebug()<<"QtConcurrent线程Id"<<QThread::currentThreadId();
}
主线程Id 0x2ca4
QtConcurrent线程Id 0x5d4