欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

QT通過(guò)C++線程池運(yùn)行Lambda自定義函數(shù)流程詳解

 更新時(shí)間:2022年10月09日 09:15:47   作者:cpp_learners  
最近在接觸公司的一個(gè)QT桌面項(xiàng)目,其中里面有一個(gè)模塊是使用線程池去運(yùn)行自定義函數(shù)的,自己潛心研究那個(gè)線程池代碼一天,發(fā)現(xiàn)研究不透,看不懂,里面幾乎都是使用C++11的新特性進(jìn)行編寫(xiě)

這里將其封裝,進(jìn)行調(diào)用使用,非常好用,遂記錄下來(lái)!

線程池代碼是國(guó)外大佬寫(xiě)的!網(wǎng)上也有好多博主進(jìn)行了轉(zhuǎn)載!

這篇博客也算是代碼積累吧,只是將這種用法記錄下載,后期如果遇到其他項(xiàng)目,可以直接在博客里拷貝代碼到項(xiàng)目中去使用,甚是方便!

我所封裝的效果是:

在一個(gè)函數(shù)里面,有一些特定需要處理的操作,得讓他在線程中去運(yùn)行,遂在處理過(guò)程中,顯示一個(gè)窗體在提示,正在處理中,如下:

一、下面是國(guó)外大佬的線程池代碼

threadpool.h

就一個(gè)頭文件搞定,方便!

#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;        // 存儲(chǔ)用戶設(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)閉時(shí)自動(dòng)釋放內(nèi)存
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 初始化智能指針線程池
    m_pThreadPools = std::make_shared<ThreadPool>(2);
    // 設(shè)置動(dòng)圖
    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è)置動(dòng)圖
    movie->setScaledSize(pSize);    // QMovie設(shè)在大小與Label一致
    movie->start();                 // 啟動(dòng)
}
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文件就兩個(gè)Label,自己去定義就好了,或者根據(jù)自己的項(xiàng)目需要去整

三、最后在主類中進(jìn)行封裝調(diào)用即可

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
	// 封裝
    int ShowLoadingDlg(std::function<void ()> pUserThreadFunction, const std::string &strTips);
    // 測(cè)試
    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;
        // 此處省略一萬(wàn)行代碼
        sleep(3);
        /* 這里可以有一個(gè)判斷,如果某個(gè)條件變量被修改了,就return退出 */
        /*
			if (true == this->indexFlag) {
				return;
			}
		*/
		// 此處還省略一萬(wàn)行代碼,此時(shí)如果上面退出了,這一萬(wàn)行代碼就沒(méi)法執(zhí)行了
		// 正常使用法,應(yīng)該是auto userThreadFunction 一進(jìn)來(lái)就應(yīng)該是一個(gè)for循環(huán)在不斷運(yùn)行,當(dāng)遇到true == this->indexFlag,
		// 就break掉,也就不會(huì)再繼續(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();即可!

四、最后

沒(méi)啥的了,代碼運(yùn)用就是這樣了。

另外,如果想要窗體可以鼠標(biāo)點(diǎn)擊移動(dòng),重寫(xiě)以下方法即可:

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;
/* 方法實(shí)現(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)閉掉,那就定義一個(gè)按鈕放在右上角,實(shí)現(xiàn)槽函數(shù),進(jìn)行關(guān)閉即可。

如果想要關(guān)閉后,也停止函數(shù)的運(yùn)行,那么可以定義QWidget變量,保存父類指針,再關(guān)閉前獲取父類指針后做一些操作后再進(jìn)行關(guān)閉即可,例如:

1. 也就是private加一個(gè)QWidget變量
private:
    QWidget *m_parent;

2. 構(gòu)造函數(shù)將傳過(guò)來(lái)的夫指針初始化他
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對(duì)象
    {
        父類對(duì)象* p = static_cast<父類對(duì)象*>(m_parent);
        if(p)
        {
            1. 這里可以調(diào)用父類的一些公開(kāi)方法,進(jìn)行以下處理
            2. 例如改變一些條件變量的值,在上傳或者下載文件中進(jìn)行判斷這個(gè)條件變量,如果值發(fā)生改變了,就停止操作,退出即可!
            3. 假設(shè)父類有一個(gè)public方法:void setStopThread(bool flag) { this->indexFlag = flag }
            4. 那么這里就可以直接使用p去調(diào)用了,p->setStopThread(true);
            5. 設(shè)置完后,父類的this->indexFlag變量被賦值true,然后在具體位置對(duì)其進(jìn)行判斷做處理就行
            6. 例如可以參考上面代碼:void MainWindow::testLoadFuncOperate() 里的注釋
        }
    }

    this->done(0);    // 返回 0
    this->close();    // 關(guān)閉窗口
}

第四點(diǎn)是專門(mén)記錄給自己看的,也是項(xiàng)目的一些用法!

到此這篇關(guān)于QT通過(guò)C++線程池運(yùn)行Lambda函數(shù)流程詳解的文章就介紹到這了,更多相關(guān)QT Lambda函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論