詳解C++中future和promise的使用
future和promise的作用是在不同線程之間傳遞數(shù)據(jù)。使用指針也可以完成數(shù)據(jù)的傳遞,但是指針非常危險(xiǎn),因?yàn)榛コ饬坎荒茏柚怪羔樀脑L問;而且指針的方式傳遞的數(shù)據(jù)是固定的,如果更改數(shù)據(jù)類型,那么還需要更改有關(guān)的接口,比較麻煩;promise支持泛型的操作,更加方便編程處理。
假設(shè)線程1需要線程2的數(shù)據(jù),那么組合使用方式如下:
線程1初始化一個promise對象和一個future對象,promise傳遞給線程2,相當(dāng)于線程2對線程1的一個承諾;future相當(dāng)于一個接受一個承諾,用來獲取未來線程2傳遞的值
線程2獲取到promise后,需要對這個promise傳遞有關(guān)的數(shù)據(jù),之后線程1的future就可以獲取數(shù)據(jù)了。
如果線程1想要獲取數(shù)據(jù),而線程2未給出數(shù)據(jù),則線程1阻塞,直到線程2的數(shù)據(jù)到達(dá)

future對象是std::async、std::promise、std::packaged_task的底層對象,用來傳遞其他線程中操作的數(shù)據(jù)結(jié)果。
std::promise的作用就是提供一個不同線程之間的數(shù)據(jù)同步機(jī)制,它可以存儲一個某種類型的值,并將其傳遞給對應(yīng)的future, 即使這個future不在同一個線程中也可以安全的訪問到這個值。
/** @file 20190815future.cpp
* @note
* @brief
* @author
* @date 2019-8-15
* @note
* @history
* @warning
*/
#include <iostream>
#include <functional>
#include <future>
#include <thread>
#include <chrono>
#include <cstdlib>
void thread_set_promise(std::promise<int>& promiseObj) {
std::cout << "In a thread, making data...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
promiseObj.set_value(35);
std::cout << "Finished\n";
}
int main() {
std::promise<int> promiseObj;
std::future<int> futureObj = promiseObj.get_future();
std::thread t(&thread_set_promise, std::ref(promiseObj));
std::cout << futureObj.get() << std::endl;
t.join();
system("pause");
return 0;
}async(高級封裝future和thread)
std::future可以從異步任務(wù)中獲取結(jié)果,一般與std::async配合使用,std::async用于創(chuàng)建異步任務(wù),實(shí)際上就是創(chuàng)建一個線程執(zhí)行相應(yīng)任務(wù)。
std::async就是異步編程的高級封裝,封裝了std::future的操作,基本上可以代替std::thread 的所有事情。
std::async的操作,其實(shí)相當(dāng)于封裝了std::promise、std::packaged_task加上std::thread。
/** @file futureIsPrime.cpp
* @note
* @brief
* @author
* @date 2019-8-15
* @note
* @history
* @warning
*/
// future example
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call function asynchronously:
std::future<bool> 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;
bool x = fut.get(); // retrieve return value
std::cout << "\n444444443 " << (x?"is":"is not") << " prime.\n";
return 0;
}std::async會首先創(chuàng)建線程執(zhí)行is_prime(444444443), 任務(wù)創(chuàng)建之后,std::async立即返回一個std::future對象。
主線程既可使用std::future::get獲取結(jié)果,如果調(diào)用過程中,任務(wù)尚未完成,則主線程阻塞至任務(wù)完成。
主線程也可使用std::future::wait_for等待結(jié)果返回,wait_for可設(shè)置超時時間,如果在超時時間之內(nèi)任務(wù)完成,則返回std::future_status::ready狀態(tài);如果在超時時間之內(nèi)任務(wù)尚未完成,則返回std::future_status::timeout狀態(tài)。
std::packaged_task用法
std::packaged_task的作用就是提供一個不同線程之間的數(shù)據(jù)同步機(jī)制,它可以存儲一個函數(shù)操作,并將其返回值傳遞給對應(yīng)的future, 而這個future在另外一個線程中也可以安全的訪問到這個值。
// packaged_task example
#include <iostream> // std::cout
#include <future> // std::packaged_task, std::future
#include <chrono> // std::chrono::seconds
#include <thread> // std::thread, std::this_thread::sleep_for
// count down taking a second for each value:
int countdown (int from, int to) {
for (int i=from; i!=to; --i) {
std::cout << i << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Lift off!\n";
return from-to;
}
int main ()
{
std::packaged_task<int(int,int)> tsk (countdown); // set up packaged_task
std::future<int> ret = tsk.get_future(); // get future
std::thread th (std::move(tsk),10,0); // spawn thread to count down from 10 to 0
// ...
int value = ret.get(); // wait for the task to finish and get result
std::cout << "The countdown lasted for " << value << " seconds.\n";
th.join();
return 0;
}到此這篇關(guān)于詳解C++中future和promise的使用的文章就介紹到這了,更多相關(guān)C++ future promise內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Qt自帶的媒體模塊實(shí)現(xiàn)播放mp4文件
這篇文章主要為大家詳細(xì)介紹了如何使用Qt自帶的媒體模塊,播放mp4等媒體文件功能,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下2024-04-04
一文帶你深入了解Qt中的順序容器類與關(guān)聯(lián)容器類
Qt中也有很多容器類,他們在存取速度、內(nèi)存開銷等方面進(jìn)行了優(yōu)化,使用起來更輕量級、更便捷,下面就跟隨小編一起來學(xué)習(xí)一下它們的具體使用吧2024-04-04
C語言中g(shù)etchar()的返回類型為什么是int詳解
這篇文章主要給大家介紹了關(guān)于C語言中g(shù)etchar()的返回類型為什么是int的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
C語言動態(tài)內(nèi)存分配函數(shù)的實(shí)現(xiàn)
這篇文章主要介紹了C語言動態(tài)內(nèi)存分配函數(shù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05

