QT通過C++線程池運(yùn)行Lambda自定義函數(shù)流程詳解
這里將其封裝,進(jìn)行調(diào)用使用,非常好用,遂記錄下來!
線程池代碼是國外大佬寫的!網(wǎng)上也有好多博主進(jìn)行了轉(zhuǎn)載!
這篇博客也算是代碼積累吧,只是將這種用法記錄下載,后期如果遇到其他項目,可以直接在博客里拷貝代碼到項目中去使用,甚是方便!
我所封裝的效果是:
在一個函數(shù)里面,有一些特定需要處理的操作,得讓他在線程中去運(yùn)行,遂在處理過程中,顯示一個窗體在提示,正在處理中,如下:

一、下面是國外大佬的線程池代碼
threadpool.h
就一個頭文件搞定,方便!
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
class ThreadPool {
public:
ThreadPool(size_t);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
#endif // THREAD_POOL_H這里面運(yùn)用了很多C++11的新特性,
代碼我是看不懂,有興趣的可以自己研究一下!
二、下面是我封裝的類
.h
#ifndef LOADFUNCOPERATE_H
#define LOADFUNCOPERATE_H
#include <QDialog>
#include <unistd.h>
#include "threadpool.h"
namespace Ui {
class LoadFuncOperate;
}
class LoadFuncOperate : public QDialog
{
Q_OBJECT
public:
explicit LoadFuncOperate(QDialog *parent = nullptr);
~LoadFuncOperate();
// 設(shè)置需要運(yùn)行的函數(shù)
void setOperateFunc(std::function<void()> userThreadOperateFunc);
// 設(shè)置顯示標(biāo)題
void setTitleHint(const std::string str);
private:
Ui::LoadFuncOperate *ui;
std::function<void()> m_pThreadFunction; // 存儲用戶設(shè)置的函數(shù)
std::shared_ptr<ThreadPool> m_pThreadPools; // 智能指針定義線程池
};
#endif // LOADFUNCOPERATE_H.cpp
#include "LoadFuncOperate.h"
#include "ui_LoadFuncOperate.h"
#include <QMovie>
LoadFuncOperate::LoadFuncOperate(QDialog *parent) :
QDialog(parent),
ui(new Ui::LoadFuncOperate)
{
ui->setupUi(this);
setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
// 設(shè)置窗體關(guān)閉時自動釋放內(nèi)存
this->setAttribute(Qt::WA_DeleteOnClose);
// 初始化智能指針線程池
m_pThreadPools = std::make_shared<ThreadPool>(2);
// 設(shè)置動圖
QMovie *movie = new QMovie(this);
movie->setFileName(":/msgbox/pro.gif"); // 設(shè)置顯示的gif圖(先將gif添加到資源文件)
QSize pSize(301, 20); // Label大小
ui->label_2->setMovie(movie); // Label設(shè)置動圖
movie->setScaledSize(pSize); // QMovie設(shè)在大小與Label一致
movie->start(); // 啟動
}
LoadFuncOperate::~LoadFuncOperate()
{
delete ui;
}
void LoadFuncOperate::setOperateFunc(std::function<void ()> userThreadOperateFunc)
{
m_pThreadFunction = userThreadOperateFunc;
auto Fun = [=]()
{
if (m_pThreadFunction)
{
sleep(1);
m_pThreadFunction(); // 執(zhí)行函數(shù)
done(1); // exec()運(yùn)行窗體后返回1
this->close();
}
};
// 運(yùn)行調(diào)用
m_pThreadPools->enqueue(Fun);
}
void LoadFuncOperate::setTitleHint(const std::string str)
{
ui->label->setText(QString::fromStdString(str));
}ui文件
ui文件就兩個Label,自己去定義就好了,或者根據(jù)自己的項目需要去整

三、最后在主類中進(jìn)行封裝調(diào)用即可
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
// 封裝
int ShowLoadingDlg(std::function<void ()> pUserThreadFunction, const std::string &strTips);
// 測試
void testLoadFuncOperate();void MainWindow::testLoadFuncOperate()
{
int a = 1;
int b = 2;
int c;
auto userThreadFunction = [&]()
{
printf("在線程中執(zhí)行函數(shù)...\n");
for (int i = 0; i < 5; i++) {
a+=2;
b--;
printf("在線程中執(zhí)行函數(shù)... %d\n", i);
}
c = a + b;
// 此處省略一萬行代碼
sleep(3);
/* 這里可以有一個判斷,如果某個條件變量被修改了,就return退出 */
/*
if (true == this->indexFlag) {
return;
}
*/
// 此處還省略一萬行代碼,此時如果上面退出了,這一萬行代碼就沒法執(zhí)行了
// 正常使用法,應(yīng)該是auto userThreadFunction 一進(jìn)來就應(yīng)該是一個for循環(huán)在不斷運(yùn)行,當(dāng)遇到true == this->indexFlag,
// 就break掉,也就不會再繼續(xù)for循環(huán)了!
printf("線程中執(zhí)行函數(shù)結(jié)束\n");
};
ShowLoadingDlg(userThreadFunction, "使用線程池執(zhí)行函數(shù)中...");
printf("c = %d\n", c);
}
int MainWindow::ShowLoadingDlg(std::function<void ()> pUserThreadFunction, const std::string &strTips)
{
LoadFuncOperate *operateFunc = new LoadFuncOperate;
operateFunc->setOperateFunc(pUserThreadFunction);
operateFunc->setTitleHint(strTips);
operateFunc->setModal(true);
int nRes = operateFunc->exec();
return nRes;
}在構(gòu)造函數(shù)中調(diào)用函數(shù)testLoadFuncOperate();即可!
四、最后
沒啥的了,代碼運(yùn)用就是這樣了。
另外,如果想要窗體可以鼠標(biāo)點擊移動,重寫以下方法即可:
protected:
void mouseMoveEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
private:
bool m_mousePress; /* 鼠標(biāo)按下 */
QPoint m_widgetPos;
/* 方法實現(xiàn) */
void LoadFuncOperate::mouseMoveEvent(QMouseEvent* event)
{
if (m_mousePress) {
move(event->pos() - m_widgetPos + this->pos());
}
}
void LoadFuncOperate::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::MouseButton::LeftButton) {
m_widgetPos = event->pos();
m_mousePress = true;
}
}
void LoadFuncOperate::mouseReleaseEvent(QMouseEvent* event)
{
m_mousePress = false;
}另外,窗體中我去掉了右上角的關(guān)閉按鈕,如果想要關(guān)閉掉,那就定義一個按鈕放在右上角,實現(xiàn)槽函數(shù),進(jìn)行關(guān)閉即可。
如果想要關(guān)閉后,也停止函數(shù)的運(yùn)行,那么可以定義QWidget變量,保存父類指針,再關(guān)閉前獲取父類指針后做一些操作后再進(jìn)行關(guān)閉即可,例如:
1. 也就是private加一個QWidget變量
private:
QWidget *m_parent;2. 構(gòu)造函數(shù)將傳過來的夫指針初始化他
LoadFuncOperate::LoadFuncOperate(QDialog *parent) :
QDialog(parent),
ui(new Ui::LoadFuncOperate)
{
ui->setupUi(this);this->m_parent= parent;
}
3. 關(guān)閉按鈕的槽函數(shù)
void LoadFuncOperate::on_pBtn_Close_clicked()
{
if(m_parent) // m_parent是父類指針,QWidget對象
{
父類對象* p = static_cast<父類對象*>(m_parent);
if(p)
{
1. 這里可以調(diào)用父類的一些公開方法,進(jìn)行以下處理
2. 例如改變一些條件變量的值,在上傳或者下載文件中進(jìn)行判斷這個條件變量,如果值發(fā)生改變了,就停止操作,退出即可!
3. 假設(shè)父類有一個public方法:void setStopThread(bool flag) { this->indexFlag = flag }
4. 那么這里就可以直接使用p去調(diào)用了,p->setStopThread(true);
5. 設(shè)置完后,父類的this->indexFlag變量被賦值true,然后在具體位置對其進(jìn)行判斷做處理就行
6. 例如可以參考上面代碼:void MainWindow::testLoadFuncOperate() 里的注釋
}
}this->done(0); // 返回 0
this->close(); // 關(guān)閉窗口
}
第四點是專門記錄給自己看的,也是項目的一些用法!
到此這篇關(guān)于QT通過C++線程池運(yùn)行Lambda函數(shù)流程詳解的文章就介紹到這了,更多相關(guān)QT Lambda函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
應(yīng)用程序操作NorFlash示例代碼分享(norflash接口使用方法)
相對于操作NandFlash,操作NorFlash相對簡單,因為基本不需要考慮壞塊,NorFlash也沒有OOB區(qū)域,也跟ECC沒有關(guān)系。讀寫擦除相對容易,下面看個例子吧2013-12-12
VC通過托盤圖標(biāo)得到該所屬進(jìn)程的實現(xiàn)代碼
這篇文章主要介紹了VC通過托盤圖標(biāo)得到該所屬進(jìn)程的實現(xiàn)代碼,為了方便大家使用特將多個代碼分享給大家,需要的朋友可以參考下2021-10-10

