QThread
繼承QThread類構建線程,可以使用信號槽通信
class Thread : public QThread
{
Q_OBJECT
public:
void setStop();
protected:
void run();
signals:
void sgl_SendMsg(); //自己的信號,可在線程進行中發送消息
private:
bool m_isStopped; //保證線程正常結束
};
void Thread::run()
{
while(!m_isStopped)
{
//主體
}
m_isStopped = false;
}
void Thread::setStop()
{
m_isStopped = true;
}
QThreadPool
Qt的線程池
You may need to create and destroy threads frequently, as managing QThread instances by hand can become cumbersome. For this, you can use the QThreadPool class, which manages a pool of reusable QThreads.
——《Mastring Qt5》
#include <QCoreApplication>
#include <QObject>
#include <QRunnable>
#include <QThread>
#include <QThreadPool>
#include <QDebug>
class HelloWorldTask : public QRunnable
{
// 線程執行任務:每間隔10s打印出線程的信息
void run()
{
qDebug() << QThread::currentThread();
QThread::msleep(10000);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThreadPool::globalInstance()->setMaxThreadCount(8);
for (int nNum = 0; nNum < 100; nNum++)
{
HelloWorldTask *task = new HelloWorldTask;
QThreadPool::globalInstance()->start(task);
}
return a.exec();
}
Qt Concurrent
Another approach to multi-threaded development is available with the Qt Concurrent framework. It is a higher-level API that avoids the use of mutexes/lock/wait conditions and promotes the distribution of the processing among CPU cores.
——《Mastring Qt5》
函數級別的多線程。當界面操作比較費時時,可使用Qt Concurrent將邏輯放在新線程中防止界面卡頓。
QFutureWatcher<void> watcher;
void longRunningFunction();
QFuture<void> future; //QFuture 用來返回QtConcurrent::run()的執行結果
future = QtConcurrent::run(longRunningFunction); //將會在默認的線程池中獲取一個線程來執行函數函數longRunningFunction()
watcher.setFuture(future); //用來監視函數結果