2. Qt深入 线程
1. QThread
参考:https://blog.csdn.net/island1314/article/details/146461320
1.1 使用重写run函数的方法
这种情况下只有run函数是运行在新线程里,QThread子类的槽函数、成员函数都是运行在主线程
class MyThread : public QThread
{Q_OBJECT
public:void run() {while(1) { qDebug() << "run thread:" << QThread::currentThreadId(); sleep(10000);}}void publicFunc() {qDebug() << "publicFunc thread:" << QThread::currentThreadId();}
public slots:void slot1() {qDebug() << "slot thread:" << QThread::currentThreadId();}
};MyThread* thread1 = new MyThread();connect(this, SIGNAL(notify()), thread1, SLOT(slot1()));thread1->start();thread1->publicFunc();emit notify();
运行结果:可以看到成员函数和槽函数运行在主线程

1.2 moveToThread
使用moveToThread将object子类对象(例如worker类)移到线程处理,这种情况下,worker类的成员函数依然在主函数运行,而槽函数则在新线程运行
class Worker : public QObject
{Q_OBJECT
public:void publicFunc() {qDebug() <<"publicFunc thread:"<<QThread::currentThreadId();}
public slots:void work1() {qDebug() <<"work1 thread:"<<QThread::currentThreadId();}void work2() {qDebug() <<"work2 thread:"<<QThread::currentThreadId();}
};thread = new QThread();worker = new Worker();worker->moveToThread(thread);connect(thread, SIGNAL(started()), worker, SLOT(work1()));connect(this, SIGNAL(notify()), worker, SLOT(work2()));thread->start();worker->publicFunc();emit notify(); //主线程发送信号,触发worker的槽函数依然运行在新线程
运行结果:可以看到成员函数运行在主线程,而槽函数无论是由thread的信号触发还是主线程的信号触发,都是运行在新线程

2. QThreadPool
https://blog.csdn.net/zyhse/article/details/109517671
3. QtConcurrent (高级用法)
https://www.feijiblog.com/blog/threadqtconcurrent1
https://blog.csdn.net/jongden/article/details/152814259

总结

