future和promise的作用是在不同線程之間傳遞數(shù)據(jù)葱色。使用指針也可以完成數(shù)據(jù)的傳遞廊营,但是指針非常危險(xiǎn),因?yàn)榛コ饬坎荒茏柚怪羔樀脑L問任斋;而且指針的方式傳遞的數(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è)承諾鉴分,用來獲取未來線程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;
}