最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++中的std::funture和std::promise實(shí)例詳解

 更新時(shí)間:2024年05月20日 11:57:58   作者:vegetablesssss  
在線程池中獲取線程執(zhí)行函數(shù)的返回值時(shí),通常使用 std::future 而不是 std::promise 來(lái)傳遞返回值,這篇文章主要介紹了C++中的std::funture和std::promise實(shí)例詳解,需要的朋友可以參考下

std::funture和std::promise

#include <iostream>
#include <thread>
#include <future>
void calculateResult(std::promise<int>& promiseObj) {
	// 模擬耗時(shí)計(jì)算
	std::this_thread::sleep_for(std::chrono::seconds(2));
	// 設(shè)置結(jié)果到 promise 中
	promiseObj.set_value(42);
}
int main() {
	// 創(chuàng)建一個(gè) promise 對(duì)象
	std::promise<int> promiseObj;
	// 獲取與 promise 關(guān)聯(lián)的 future
	std::future<int> futureObj = promiseObj.get_future();
	// 啟動(dòng)一個(gè)新的線程執(zhí)行計(jì)算
	std::thread workerThread(calculateResult, std::ref(promiseObj));
	// 在主線程中等待任務(wù)完成,并獲取結(jié)果
	int result = futureObj.get();
	std::cout << "Result: " << result << std::endl;
	// 等待工作線程結(jié)束
	workerThread.join();
	return 0;
}

使用future和promise可以獲取到線程執(zhí)行函數(shù)的結(jié)果,類似C#實(shí)現(xiàn)

#include <iostream>
#include <thread>
#include <future>
#include <vector>
#include <functional>
#include <queue>
class ThreadPool {
public:
    explicit ThreadPool(size_t numThreads) : stop(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            threads.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(mutex);
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) {
                            return;
                        }
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
                });
        }
    }
    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(mutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread& thread : threads) {
            thread.join();
        }
    }
    template <class F, class... Args>
    auto 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> result = task->get_future();
        {
            std::unique_lock<std::mutex> lock(mutex);
            if (stop) {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }
            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return result;
    }
private:
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> tasks;
    std::mutex mutex;
    std::condition_variable condition;
    bool stop;
};
int calculateResult() {
    // 模擬耗時(shí)計(jì)算
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}
int main() {
    ThreadPool pool(4);
    std::future<int> futureObj = pool.enqueue(calculateResult);
    int result = futureObj.get();
    std::cout << "Result: " << result << std::endl;
    return 0;
}

在線程池中獲取線程執(zhí)行函數(shù)的返回值時(shí),通常使用 std::future 而不是 std::promise 來(lái)傳遞返回值。這是因?yàn)榫€程池內(nèi)部已經(jīng)管理了任務(wù)的執(zhí)行和結(jié)果的傳遞,你只需要將任務(wù)提交給線程池,并使用 std::future 來(lái)獲取結(jié)果。

線程池內(nèi)部一般會(huì)使用一個(gè)任務(wù)隊(duì)列來(lái)存儲(chǔ)待執(zhí)行的任務(wù),并使用一個(gè)線程池管理器來(lái)調(diào)度任務(wù)的執(zhí)行。當(dāng)你向線程池提交任務(wù)時(shí),線程池會(huì)選擇一個(gè)空閑的線程來(lái)執(zhí)行任務(wù),并將結(jié)果存儲(chǔ)在與任務(wù)關(guān)聯(lián)的 std::future 對(duì)象中。

擴(kuò)展:C# 異步

首先說(shuō)幾個(gè)關(guān)鍵詞:

async:修飾方法,表明該方法是異步的
Task:異步任務(wù),可以作為異步方法的返回值
await:等待異步方法執(zhí)行完成,只能在異步方法中使用
TaskCompletionSource:可通過(guò)SetResult方法來(lái)設(shè)置異步的結(jié)果

using System;
using System.Threading.Tasks;
class Program
{
    static async void AsyncMethod()
    {
        await Task.Run(() =>
        {
            Console.WriteLine("耗時(shí)操作");
        });
        await AsyncTaskCompletion();
    }
    static async Task<int> AsyncTaskCompletion()
    {
        Console.WriteLine("AsyncTaskCompletion Start");
        TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
        // 模擬異步操作
        await Task.Delay(3000).ContinueWith(task =>
        {
            if (task.Exception != null)
            {
                tcs.SetException(task.Exception);
            }
            else
            {
                // 設(shè)置異步操作的結(jié)果
                tcs.SetResult(42);
            }
        });
        Console.WriteLine("AsyncTaskCompletion END");
        return await tcs.Task;
    }
    static void Main()
    {
        Console.WriteLine("Main Start");
        AsyncMethod(); 
        Console.WriteLine("Main END");
        Console.ReadLine();
    }
}

main方法中執(zhí)行一個(gè)返回值為空的異步方法AsyncMethod,在AsyncMethod可以執(zhí)行各種耗時(shí)操作而不影響main方法執(zhí)行。
在AsyncTaskCompletion方法中等待tcs.SetResult方法執(zhí)行后才會(huì)返回,可用于在回調(diào)函數(shù)中設(shè)置結(jié)果。

到此這篇關(guān)于C++中的std::funture和std::promise實(shí)例詳解的文章就介紹到這了,更多相關(guān)std::funture和std::promise內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • VC程序設(shè)計(jì)中CreateProcess用法注意事項(xiàng)

    VC程序設(shè)計(jì)中CreateProcess用法注意事項(xiàng)

    這篇文章主要介紹了VC程序設(shè)計(jì)中CreateProcess用法注意事項(xiàng),需要的朋友可以參考下
    2014-07-07
  • 非常經(jīng)典的C語(yǔ)言趣味題目

    非常經(jīng)典的C語(yǔ)言趣味題目

    在這個(gè)網(wǎng)站上發(fā)現(xiàn)一套很有趣的C語(yǔ)言測(cè)試題,如果你招聘C語(yǔ)言相關(guān)開(kāi)發(fā)人員,或者正在學(xué)習(xí)C語(yǔ)言,很值得做一做
    2013-04-04
  • C++11范圍for初始化列表auto decltype詳解

    C++11范圍for初始化列表auto decltype詳解

    C++11引入auto類型推導(dǎo)、decltype類型推斷、統(tǒng)一列表初始化、范圍for循環(huán)及智能指針,提升代碼簡(jiǎn)潔性、類型安全與資源管理效率
    2025-07-07
  • C語(yǔ)言實(shí)現(xiàn)學(xué)生管理系統(tǒng)總結(jié)

    C語(yǔ)言實(shí)現(xiàn)學(xué)生管理系統(tǒng)總結(jié)

    這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-07-07
  • C++生成格式化的標(biāo)準(zhǔn)字符串實(shí)例代碼

    C++生成格式化的標(biāo)準(zhǔn)字符串實(shí)例代碼

    這篇文章主要給大家介紹了關(guān)于C++生成格式化的標(biāo)準(zhǔn)字符串的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用C++具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • C/C++ 中堆和棧及靜態(tài)數(shù)據(jù)區(qū)詳解

    C/C++ 中堆和棧及靜態(tài)數(shù)據(jù)區(qū)詳解

    這篇文章主要介紹了C/C++ 中堆和棧及靜態(tài)數(shù)據(jù)區(qū)詳解的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • C++第三方日志庫(kù)Glog的安裝與使用介紹

    C++第三方日志庫(kù)Glog的安裝與使用介紹

    這篇文章主要介紹了C++第三方日志庫(kù)Glog的安裝與使用介紹,本文配置所采用的環(huán)境為Visual?Studio2017,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-02-02
  • 使用C++實(shí)現(xiàn)順序鏈表

    使用C++實(shí)現(xiàn)順序鏈表

    今天小編就為大家分享一篇關(guān)于使用C++實(shí)現(xiàn)順序鏈表,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-12-12
  • socket多人聊天程序C語(yǔ)言版(二)

    socket多人聊天程序C語(yǔ)言版(二)

    這篇文章主要為大家詳細(xì)介紹了socket多人聊天程序C語(yǔ)言版第二篇,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • C++ min/max_element 函數(shù)用法詳解

    C++ min/max_element 函數(shù)用法詳解

    這篇文章主要介紹了C++ min/max_element 函數(shù)用法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-02-02

最新評(píng)論

沙湾县| 周至县| 土默特左旗| 清涧县| 铜鼓县| 历史| 图片| 克什克腾旗| 越西县| 盐亭县| 老河口市| 怀仁县| 灵武市| 巨鹿县| 常州市| 包头市| 大同市| 栾城县| 江陵县| 肇源县| 西充县| 上栗县| 孟连| 娄底市| 方山县| 南江县| 阿克陶县| 怀集县| 西安市| 磴口县| 韶山市| 静宁县| 永和县| 同江市| 佛学| 海晏县| 舟曲县| 晋城| 昂仁县| 班戈县| 玉门市|