1 QThread 類概述
QThread類為用戶管理多線程提供了一種平臺無關的途徑。
include <QThread>
2 詳述
QThread對象在程序內(nèi)部進行控制線程的管理疮蹦,QThread起始于run()函數(shù)額執(zhí)行煞茫。默認情況下,run()通過調(diào)用exec()啟動事件循環(huán)(event loop),并在線程內(nèi)部執(zhí)行Qt 的事件循環(huán)。
線程在程序中用途非常廣,常常用于避免程序阻塞疮方、分布式計算、多任務協(xié)作等功能茧彤。
有的朋友為了達到程序不阻塞骡显、提高運行效率等效果喜歡在一個程序中生成幾十甚至幾百個線程,然而需要注意的是,很多時候線程太多并不能提高效率惫谤,如果線程沒有休眠或者等待的話壁顶,最多同時運行的數(shù)量是CPU的核心數(shù)量,CPU需要在諸多線程中切換和調(diào)度溜歪,反而降低了系統(tǒng)效率若专。而在另一種情況,如果線程大部分時間是等待(如等待某個返回蝴猪、讀取硬盤等)调衰,那么數(shù)量稍微增多些的確會提高效率。
所以歸納起來:
- 以計算為主的運算密集型線程數(shù)量理論上只要為CPU核心數(shù)量即可自阱,如使用線程計算質(zhì)數(shù)組合解析數(shù)據(jù)等嚎莉。
- 以等待為主的IO密集型線程數(shù)量可以按照具體業(yè)務規(guī)模適當增加線程,如使用線程讀寫數(shù)據(jù)庫沛豌、硬盤萝喘、遠程接口獲取數(shù)據(jù)等(具體項目中可以增加的線程而不影響運行效率的閥值需要不同項目具體測試得出)
3 QT中使用多線程
Qt中如何創(chuàng)建使用線程,非常簡單琼懊,只需要繼分為三步:
- 1 創(chuàng)建線程類,繼承QThread
- 2重寫run()
- 3主線程中創(chuàng)建線程對象爬早,使用start()方法啟動線程哼丈。
(1) 首先,新建Qt命令行項目筛严,在項目中創(chuàng)建線程類:
CSimpleThread.h
#ifndef CSIMPLETHREAD_H
#define CSIMPLETHREAD_H
#include <QThread>
class CSimpleThread : public QThread
{
Q_OBJECT
public:
CSimpleThread();
};
#endif // CSIMPLETHREAD_H
CSimpleThread.cpp
#include "CSimpleThread.h"
#include <QDebug>
CSimpleThread::CSimpleThread()
{
}
(2) 重寫run()醉旦,每5秒打印一句話
CSimpleThread.h
#ifndef CSIMPLETHREAD_H
#define CSIMPLETHREAD_H
#include <QThread>
class CSimpleThread : public QThread
{
Q_OBJECT
public:
CSimpleThread();
void run();
};
#endif // CSIMPLETHREAD_H
CSimpleThread.cpp
#include "CSimpleThread.h"
#include <QDebug>
CSimpleThread::CSimpleThread()
{
}
void CSimpleThread::run()
{
while (true) {
qDebug()<<"CSimpleThread run!";
sleep(5);
}
}
(3) 主線程中創(chuàng)建線程對象,使用start()方法啟動線程
main.cpp
#include <QCoreApplication>
#include <CSimpleThread.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CSimpleThread *SThread = new CSimpleThread();
SThread->start();
return a.exec();
}
參考文獻:千荒箭