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

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

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

這里將其封裝,進行調用使用,非常好用,遂記錄下來!

線程池代碼是國外大佬寫的!網(wǎng)上也有好多博主進行了轉載!

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

我所封裝的效果是:

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

一、下面是國外大佬的線程池代碼

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

這里面運用了很多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ù)
    void setOperateFunc(std::function<void()> userThreadOperateFunc);
    // 設置顯示標題
    void setTitleHint(const std::string str);
private:
    Ui::LoadFuncOperate *ui;
    std::function<void()> m_pThreadFunction;        // 存儲用戶設置的函數(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);
    // 設置窗體關閉時自動釋放內存
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 初始化智能指針線程池
    m_pThreadPools = std::make_shared<ThreadPool>(2);
    // 設置動圖
    QMovie *movie = new QMovie(this);
    movie->setFileName(":/msgbox/pro.gif");     // 設置顯示的gif圖(先將gif添加到資源文件)
    QSize pSize(301, 20);           // Label大小
    ui->label_2->setMovie(movie);   // Label設置動圖
    movie->setScaledSize(pSize);    // QMovie設在大小與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()運行窗體后返回1
            this->close();
        }
    };
    // 運行調用
    m_pThreadPools->enqueue(Fun);
}
void LoadFuncOperate::setTitleHint(const std::string str)
{
    ui->label->setText(QString::fromStdString(str));
}

ui文件

ui文件就兩個Label,自己去定義就好了,或者根據(jù)自己的項目需要去整

三、最后在主類中進行封裝調用即可

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í)行了
		// 正常使用法,應該是auto userThreadFunction 一進來就應該是一個for循環(huán)在不斷運行,當遇到true == this->indexFlag,
		// 就break掉,也就不會再繼續(xù)for循環(huán)了!

        printf("線程中執(zhí)行函數(shù)結束\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;
}

在構造函數(shù)中調用函數(shù)testLoadFuncOperate();即可!

四、最后

沒啥的了,代碼運用就是這樣了。

另外,如果想要窗體可以鼠標點擊移動,重寫以下方法即可:

protected:
    void mouseMoveEvent(QMouseEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
private:
	bool m_mousePress;      /* 鼠標按下 */
	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;
}

另外,窗體中我去掉了右上角的關閉按鈕,如果想要關閉掉,那就定義一個按鈕放在右上角,實現(xiàn)槽函數(shù),進行關閉即可。

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

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

2. 構造函數(shù)將傳過來的夫指針初始化他
LoadFuncOperate::LoadFuncOperate(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::LoadFuncOperate)
{
        ui->setupUi(this);

        this->m_parent= parent;
}
3. 關閉按鈕的槽函數(shù)
void LoadFuncOperate::on_pBtn_Close_clicked()
{
    if(m_parent)    // m_parent是父類指針,QWidget對象
    {
        父類對象* p = static_cast<父類對象*>(m_parent);
        if(p)
        {
            1. 這里可以調用父類的一些公開方法,進行以下處理
            2. 例如改變一些條件變量的值,在上傳或者下載文件中進行判斷這個條件變量,如果值發(fā)生改變了,就停止操作,退出即可!
            3. 假設父類有一個public方法:void setStopThread(bool flag) { this->indexFlag = flag }
            4. 那么這里就可以直接使用p去調用了,p->setStopThread(true);
            5. 設置完后,父類的this->indexFlag變量被賦值true,然后在具體位置對其進行判斷做處理就行
            6. 例如可以參考上面代碼:void MainWindow::testLoadFuncOperate() 里的注釋
        }
    }

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

第四點是專門記錄給自己看的,也是項目的一些用法!

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

相關文章

  • C++ 函數(shù)指針詳細總結

    C++ 函數(shù)指針詳細總結

    這篇文章主要介紹了C++ 函數(shù)指針內容,下面文章圍繞C++ 函數(shù)指針的相關資料展開詳細內容,包括函數(shù)指針的進階內容,需要的朋友可以參考一下,希望對大家有所幫助
    2021-11-11
  • C++使用正則表達式的詳細教程

    C++使用正則表達式的詳細教程

    正則表達式是一個非常強大的工具,主要用于字符串匹配,下面這篇文章主要給大家介紹了關于C++使用正則表達式的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-05-05
  • 應用程序操作NorFlash示例代碼分享(norflash接口使用方法)

    應用程序操作NorFlash示例代碼分享(norflash接口使用方法)

    相對于操作NandFlash,操作NorFlash相對簡單,因為基本不需要考慮壞塊,NorFlash也沒有OOB區(qū)域,也跟ECC沒有關系。讀寫擦除相對容易,下面看個例子吧
    2013-12-12
  • DEV?C++源碼編譯后控制臺輸出中文亂碼問題解決

    DEV?C++源碼編譯后控制臺輸出中文亂碼問題解決

    本文主要介紹了DEV?C++源碼編譯后控制臺輸出中文亂碼問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01
  • C語言中char*和char[]用法區(qū)別分析

    C語言中char*和char[]用法區(qū)別分析

    這篇文章主要介紹了C語言中char*和char[]用法區(qū)別,包括使用過程中的誤區(qū)及注意點分析,需要的朋友可以參考下
    2014-09-09
  • C++中const的用法詳細總結

    C++中const的用法詳細總結

    以下是對C++中const的用法進行了詳細的總結分析,需要的朋友可以過來參考下,希望對大家有所幫助
    2013-09-09
  • 詳解C++編程中類的聲明和對象成員的引用

    詳解C++編程中類的聲明和對象成員的引用

    這篇文章主要介紹了詳解C++編程中類的聲明和對象成員的引用,是C++入門學習中的基礎知識,需要的朋友可以參考下
    2015-09-09
  • C語言實現(xiàn)3*3數(shù)組對角線之和示例

    C語言實現(xiàn)3*3數(shù)組對角線之和示例

    今天小編就為大家分享一篇C語言實現(xiàn)3*3數(shù)組對角線之和示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • C++使用curl庫進行http請求的方法詳解

    C++使用curl庫進行http請求的方法詳解

    這篇文章主要為大家詳細介紹了C++如何使用curl庫進行http請求,并且實現(xiàn)獲取返回的頭信息的時間,也就是獲取后臺服務的當前時間,感興趣的可以了解一下
    2023-07-07
  • VC通過托盤圖標得到該所屬進程的實現(xiàn)代碼

    VC通過托盤圖標得到該所屬進程的實現(xiàn)代碼

    這篇文章主要介紹了VC通過托盤圖標得到該所屬進程的實現(xiàn)代碼,為了方便大家使用特將多個代碼分享給大家,需要的朋友可以參考下
    2021-10-10

最新評論