C++之future和promise

future和promise的作用是在不同線程之間傳遞數(shù)據(jù)。使用指針也可以完成數(shù)據(jù)的傳遞,但是指針?lè)浅NkU(xiǎn),因?yàn)榛コ饬坎荒茏柚怪羔樀脑L問(wèn);而且指針的方式傳遞的數(shù)據(jù)是固定的,如果更改數(shù)據(jù)類型,那么還需要更改有關(guān)的接口,比較麻煩;promise支持泛型的操作,更加方便編程處理。

假設(shè)線程1需要線程2的數(shù)據(jù),那么組合使用方式如下:

線程1初始化一個(gè)promise對(duì)象和一個(gè)future對(duì)象,promise傳遞給線程2,相當(dāng)于線程2對(duì)線程1的一個(gè)承諾;future相當(dāng)于一個(gè)接受一個(gè)承諾,用來(lái)獲取未來(lái)線程2傳遞的值

線程2獲取到promise后,需要對(duì)這個(gè)promise傳遞有關(guān)的數(shù)據(jù),之后線程1的future就可以獲取數(shù)據(jù)了。

如果線程1想要獲取數(shù)據(jù),而線程2未給出數(shù)據(jù),則線程1阻塞,直到線程2的數(shù)據(jù)到達(dá)

/** @file? 20190815future.cpp

*? @note?

*? @brief

*? @author

*? @date? 2019-8-15

*? @note?

*? @history

*? @warning*/#include #include #include #include #include #include voidthread_set_promise(std::promise& promiseObj) {

? ? std::cout <<"In a thread, making data...";

? ? std::this_thread::sleep_for(std::chrono::milliseconds(1000));

? ? promiseObj.set_value(35);

? ? std::cout <<"Finished";

}int main() {

? ? std::promise promiseObj;

? ? std::future futureObj = promiseObj.get_future();

? ? std::thread t(&thread_set_promise, std::ref(promiseObj));

? ? std::cout << futureObj.get() << std::endl;

? ? t.join();

? ? system("pause");

? ? return0;

}

async(高級(jí)封裝future和thread)

/** @file? futureIsPrime.cpp

*? @note?

*? @brief

*? @author

*? @date? 2019-8-15

*? @note?

*? @history

*? @warning*/// future example#include // std::cout#include // std::async, std::future#include // std::chrono::milliseconds// a non-optimized way of checking for prime numbers:boolis_prime (int x) {

? for(inti=2; i

? returntrue;

}int main ()

{

? // call function asynchronously:std::future fut = std::async (is_prime,444444443);

? // do something while waiting for function to set future:std::cout <<"checking, please wait";

? std::chrono::milliseconds span (100);

? while(fut.wait_for(span)==std::future_status::timeout)

? ? std::cout <<'.'<< std::flush;

? boolx = fut.get();// retrieve return value? std::cout <<"444444443 "<< (x?"is":"is not") <<" prime.";

? return0;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容