Qt/C++在子線程執行函數的兩種方法

前言:

很多時候,我們的某個函數非常耗時,會造成系統卡頓,但這個函數又不會經常調用,如果另外建立一個線程類,又得去維護,得不償失,這個時候,我們就希望在子線程執行該函數,執行完自動釋放。 這裏介紹兩個方法:

1、使用QtConcurrent

QtConcurrent 是命名空間 (namespace),它提供了高層次的函數接口 (APIs),使所寫程序,可根據計算機的 CPU 核數,自動調整運行的線程數目。

1.1、 函數原型

QFuture<T> QtConcurrent::run(QThreadPool::globalInstance(), function, ...) ;
QFuture<T> QtConcurrent::run(QThreadPool *pool, Function function, ...);

1.2、使用準備
使用QtConcurrent需要在.pro文件增加 QT += concurrent
如果是使用VS+Qt,則需要增加模塊Concurrent

1.3、實例

#include <QString>
#include <QDebug>
#include <QThread>
#include <QApplication>

#include "qtconcurrentrun.h"

using namespace QtConcurrent;

void func(QString name)
{
    qDebug() << name << "from" << QThread::currentThread();
}

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QFuture<void> fut1 = run(func, QString("Thread 1"));
    QFuture<void> fut2 = run(func, QString("Thread 2"));

    fut1.waitForFinished();
    fut2.waitForFinished();
}

運行結果如下:

"Thread 1" from QThread(0x1b74fd2ebc0, name = "Thread (pooled)")
"Thread 2" from QThread(0x1b74fd534e0, name = "Thread (pooled)")

如果頻繁使用,最好用一個線程池以減少與系統的交互

extern void func();
QThreadPool pool;
QFuture<void> future = QtConcurrent::run(&pool, func);

更多關於QtConcurrent的內容請參閱Qt幫助文檔嘿嘿^-^

2、使用Windows函數CreateThread

CreateThread百度百科

線程有兩種聲明方式
(1)DWORD WINAPI 函數名 (LPVOID lpParam); //標準格式
DWORD WINAPI 函數名 (LPVOID lpParam)
{
return 0;
}
CreateThread(NULL, 0, 函數名, 0, 0, 0);
(2)void 函數名();
使用void 函數名()此種線程聲明方式時,lpStartAddress需要加入LPTHREAD_START_ROUTINE轉換,如
void 函數名()
{
return;
}
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)函數名, 0, 0, 0);


static unsigned int func1(LPARAM lParam); 
unsigned int func1(LPARAM lParam) 
{ 
MyClass* pThis = (MyClass*)lParam;


}
HANDLE hThread; 
DWORD dwRet = 0; 
hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)func1,this,NULL,&dwRet); 
WaitForSingleObject(hThread ,INFINITE);//INFINTE表示無限期等待
CloseHandle(hThread); //關閉線程
hThread = INVALID_HANDLE_VALUE;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章