亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
Understanding std::promise and std::future
Basic usage with std::thread
Handling exceptions
Using std::async instead (simpler alternative)
首頁 后端開發(fā) C++ 如何在 C 中使用 std::future 和 std::promise 實現(xiàn)異步結(jié)果

如何在 C 中使用 std::future 和 std::promise 實現(xiàn)異步結(jié)果

Oct 15, 2025 am 02:45 AM
C++異步

std::promise和std::future用于線程間傳遞異步結(jié)果,promise通過set_value設(shè)置一次值,future通過get獲取結(jié)果并支持異常傳遞,適用于需精細(xì)控制結(jié)果設(shè)置的場景。

How to use std::future and std::promise for asynchronous results in C

When you need to retrieve a result from an asynchronous operation in C , std::future and std::promise offer a clean way to pass values between threads. A std::promise lets you set a value (or exception) at some point, and a corresponding std::future allows you to retrieve that value later, potentially in another thread.

Understanding std::promise and std::future

A std::promise is a writable object that holds a value of type T (or an exception) which can be set once. You get a std::future from the promise using get_future(). This future acts as the reader side — it can wait for and retrieve the value.

Key points:

  • Each promise is associated with exactly one future (or shared_future).
  • The value is transferred only once — after setting it via set_value(), no further updates are allowed.
  • If the future is accessed before the value is ready, it can block until available.

Basic usage with std::thread

You can use promise and future to return results from a thread manually:

#include <future><br>#include <thread><br>#include <iostream>
<p>void compute_and_set(std::promise<int>& prms) {
int result = 42; // Simulate some work
prms.set_value(result);
}</int></p>
<p>int main() {
std::promise<int> prm;
std::future<int> fut = prm.get_future();</int></int></p><pre class='brush:php;toolbar:false;'>std::thread t(compute_and_set, std::ref(prm));

std::cout << "Waiting for result...\n";
int value = fut.get(); // Blocks until value is ready
std::cout << "Got: " << value << "\n";

t.join();
return 0;

}

In this example, the thread computes a value and sets it through the promise. The main thread waits via fut.get().

Handling exceptions

A promise can also signal an error by calling set_exception():

void may_throw(std::promise<double>& prms) {
    try {
        throw std::runtime_error("Something went wrong");
    } catch (...) {
        prms.set_exception(std::current_exception());
    }
}

When fut.get() is called on the future, it will rethrow the captured exception.

Using std::async instead (simpler alternative)

In many cases, std::async is easier and more convenient. It automatically manages the promise/future pair:

auto fut = std::async([]() {
    return 7 * 6;
});
<p>std::cout << "Answer: " << fut.get() << "\n";</p>

This gives you a future directly without manually handling promises or threads.

Use std::promise when you need fine-grained control over when and where the result is set — such as in callbacks, custom thread pools, or event loops. Otherwise, std::async is often sufficient and cleaner.

Basically just match promise and future across communication boundaries, set once, get once, handle errors properly, and clean up threads.

以上是如何在 C 中使用 std::future 和 std::promise 實現(xiàn)異步結(jié)果的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Stock Market GPT

Stock Market GPT

人工智能驅(qū)動投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

如何編譯和運行C程序 如何編譯和運行C程序 Sep 16, 2025 am 05:29 AM

InstallaC compilerlikeg usingpackagemanagersordevelopmenttoolsdependingontheOS.2.WriteaC programandsaveitwitha.cppextension.3.Compiletheprogramusingg hello.cpp-ohellotogenerateanexecutable.4.Runtheexecutablewith./helloonLinux/macOSorhello.exeonWi

C自定義分配器示例 C自定義分配器示例 Sep 17, 2025 am 08:45 AM

自定義分配器可用于控制C 容器的內(nèi)存分配行為,1.示例中的LoggingAllocator通過重載allocate、deallocate、construct和destroy方法實現(xiàn)內(nèi)存操作日志記錄;2.分配器需定義value_type和rebind模板,以滿足STL容器類型轉(zhuǎn)換需求;3.分配器構(gòu)造與拷貝時觸發(fā)日志輸出,便于追蹤生命周期;4.實際應(yīng)用包括內(nèi)存池、共享內(nèi)存、調(diào)試工具和嵌入式系統(tǒng);5.C 17起construct和destroy可由std::allocator_traits默認(rèn)處理

如何在C中執(zhí)行系統(tǒng)命令 如何在C中執(zhí)行系統(tǒng)命令 Sep 21, 2025 am 04:35 AM

使用std::system()函數(shù)可執(zhí)行系統(tǒng)命令,需包含頭文件,傳入C風(fēng)格字符串命令,如std::system("ls-l"),返回值為-1表示命令處理器不可用。

如何使用CMAKE建立C項目? 如何使用CMAKE建立C項目? Sep 18, 2025 am 01:04 AM

創(chuàng)建項目目錄結(jié)構(gòu),包含CMakeLists.txt、src/和include/;2.編寫CMakeLists.txt,指定CMake版本、項目名稱、C 標(biāo)準(zhǔn)并添加可執(zhí)行文件;3.使用mkdirbuild進(jìn)入目錄并運行cmake..和cmake--build.進(jìn)行編譯;4.通過add_executable添加多個源文件,用target_include_directories包含頭文件路徑;5.使用find_package查找外部庫并用target_link_libraries鏈接;6.通過tar

如何在C中使用堆棧 如何在C中使用堆棧 Sep 21, 2025 am 05:16 AM

C 的stack是STL中的容器適配器,遵循后進(jìn)先出原則,需包含頭文件;通過push添加元素,pop移除頂部元素,top訪問棧頂,操作前應(yīng)檢查是否為空,常用于表達(dá)式求值、回溯等場景。

如何在現(xiàn)代C中使用汽車 如何在現(xiàn)代C中使用汽車 Sep 24, 2025 am 04:59 AM

Theautokeywordletsthecompilerdeducevariabletypesfrominitializers,reducingverbosityandimprovingmaintainability.Itsimplifiescodewithcomplextypeslikeiteratorsandlambdas,supportsreferencesandconstqualifierstoavoidunnecessarycopies,andadaptsautomaticallyw

如何在C中實現(xiàn)自定義迭代器 如何在C中實現(xiàn)自定義迭代器 Sep 20, 2025 am 01:13 AM

答案是定義包含必要類型別名和操作的類。首先設(shè)置value_type、reference、pointer、difference_type和iterator_category,然后實現(xiàn)解引用、遞增及比較操作,最后在容器中提供begin()和end()方法以返回迭代器實例,使其兼容STL算法和范圍for循環(huán)。

如何在C中創(chuàng)建靜態(tài)變量 如何在C中創(chuàng)建靜態(tài)變量 Sep 19, 2025 am 05:24 AM

AstaticVariableInc witherinsitvaluebetwunctioncallsandisinitializedonce.2.Inideafunction,itpreservesstataTateAcrossCalls,siseascountingIterations.3.inaclass,itissharedamondamongallinStancessandMustancessandMustancessandMustbedIendEctIndEtheClastoAvoVovoiDlinkingErrors.4.StaticvariA.StaticvAriA.StaticVariA.StaticVariA

See all articles