C++11中std::future的具體使用方法
C++11中的std::future是一個(gè)模板類。std::future提供了一種用于訪問異步操作結(jié)果的機(jī)制。std::future所引用的共享狀態(tài)不能與任何其它異步返回的對(duì)象共享(與std::shared_future相反)( std::future references shared state that is not shared with any other asynchronous return objects (as opposed to std::shared_future))。一個(gè)future是一個(gè)對(duì)象,它可以從某個(gè)提供者的對(duì)象或函數(shù)中檢索值,如果在不同的線程中,則它可以正確地同步此訪問(A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads)。
有效的future是與共享狀態(tài)(shared state)關(guān)聯(lián)的future對(duì)象,可以通過調(diào)用以下函數(shù)(provider)來(lái)構(gòu)造future對(duì)象:std::async、std::promise::get_future、std::packaged_task::get_future。future對(duì)象僅在它們是有效時(shí)才有用。
模板類std::future成員函數(shù)包括:
1. 構(gòu)造函數(shù):(1).不帶參數(shù)的默認(rèn)構(gòu)造函數(shù),此對(duì)象沒有共享狀態(tài),因此它是無(wú)效的,但是可以通過移動(dòng)賦值的方式將一個(gè)有效的future值賦值給它;(2).禁用拷貝構(gòu)造;(3).支持移動(dòng)構(gòu)造。
2. 析構(gòu)函數(shù):銷毀future對(duì)象,它是異常安全的。
3. get函數(shù):(1).當(dāng)共享狀態(tài)就緒時(shí),返回存儲(chǔ)在共享狀態(tài)中的值(或拋出異常)。(2).如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒。(3).當(dāng)共享狀態(tài)就緒后,則該函數(shù)將取消阻塞并返回(或拋出)釋放其共享狀態(tài),這使得future對(duì)象不再有效,因此對(duì)于每一個(gè)future共享狀態(tài),該函數(shù)最多應(yīng)被調(diào)用一次。(4).std::future<void>::get()不返回任何值,但仍等待共享狀態(tài)就緒并釋放它。(5).共享狀態(tài)是作為原子操作(atomic operation)被訪問。
4. operator=:(1).禁用拷貝賦值。(2).支持移動(dòng)賦值:如果在調(diào)用之前,此對(duì)象是有效的(即它已經(jīng)訪問共享狀態(tài)),則將其與先前已關(guān)聯(lián)的共享狀態(tài)解除關(guān)聯(lián)。如果它是與先前共享狀態(tài)關(guān)聯(lián)的唯一對(duì)象,則先前的共享狀態(tài)也會(huì)被銷毀。
5. share函數(shù):獲取共享的future,返回一個(gè)std::shared_future對(duì)象,該對(duì)象獲取future對(duì)象的共享狀態(tài)。future對(duì)象將不再有效。
6. valid函數(shù):檢查共享狀態(tài)的有效性,返回當(dāng)前的future對(duì)象是否與共享狀態(tài)關(guān)聯(lián)。一旦調(diào)用了std::future::get()函數(shù),再調(diào)用此函數(shù)將返回false。
7. wait函數(shù):(1).等待共享狀態(tài)就緒。(2).如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒。(3).當(dāng)共享狀態(tài)就緒后,則該函數(shù)將取消阻塞并void返回。
8. wait_for函數(shù):(1).等待共享狀態(tài)在指定的時(shí)間內(nèi)(time span)準(zhǔn)備就緒。(2). 如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒或已達(dá)到設(shè)置的時(shí)間。(3).此函數(shù)的返回值類型為枚舉類future_status。此枚舉類有三種label:ready:共享狀態(tài)已就緒;timeout:在指定的時(shí)間內(nèi)未就緒;deferred:共享狀態(tài)包含了一個(gè)延遲函數(shù)(deferred function)。
9. wait_until函數(shù):(1). 等待共享狀態(tài)在指定的時(shí)間點(diǎn)(time point)準(zhǔn)備就緒。(2). 如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒或已達(dá)到指定的時(shí)間點(diǎn)。(3).此函數(shù)的返回值類型為枚舉類future_status。
詳細(xì)用法見下面的測(cè)試代碼,下面是從其他文章中copy的測(cè)試代碼,部分作了調(diào)整,詳細(xì)內(nèi)容介紹可以參考對(duì)應(yīng)的reference:
#include "future.hpp"
#include <iostream>
#include <future>
#include <chrono>
#include <utility>
#include <thread>
namespace future_ {
///////////////////////////////////////////////////////////
// reference: http://www.cplusplus.com/reference/future/future/
int test_future_1()
{
{ // constructor/get/operator=
auto get_value = []() { return 10; };
std::future<int> foo; // default-constructed
std::future<int> bar = std::async(get_value); // move-constructed
int x = bar.get();
std::cout << "value: " << x << '\n'; // 10
//int x2 = bar.get(); // crash, 對(duì)于每個(gè)future的共享狀態(tài),get函數(shù)最多僅被調(diào)用一次
//std::cout << "value: " << x2 << '\n';
std::future<int> foo2(std::async(get_value));
std::cout << "value: " << foo2.get() << '\n'; // 10
}
{ // share
std::future<int> fut = std::async([]() { return 10; });
std::shared_future<int> shfut = fut.share();
//std::cout << "value: " << fut.get() << '\n'; // crash, 執(zhí)行完fut.share()后,fut對(duì)象將變得無(wú)效
std::cout << "fut valid: " << fut.valid() << '\n';// 0
// shared futures can be accessed multiple times:
std::cout << "value: " << shfut.get() << '\n'; // 10
std::cout << "its double: " << shfut.get() * 2 << '\n'; // 20, 對(duì)于std::shared_future對(duì)象,get函數(shù)可以被多次訪問
}
{ // valid
std::future<int> foo, bar;
foo = std::async([]() { return 10; });
bar = std::move(foo);
if (foo.valid()) std::cout << "foo's value: " << foo.get() << '\n';
else std::cout << "foo is not valid\n"; // foo is not valid
if (bar.valid()) std::cout << "bar's value: " << bar.get() << '\n'; // 10
else std::cout << "bar is not valid\n";
}
{ // wait
auto is_prime = [](int x) {
for (int i = 2; i < x; ++i) if (x%i == 0) return false;
return true;
};
// call function asynchronously:
std::future<bool> fut = std::async(is_prime, 194232491);
std::cout << "checking...\n";
fut.wait();
std::cout << "\n194232491 ";
if (fut.get()) // guaranteed to be ready (and not block) after wait returns
std::cout << "is prime.\n";
else
std::cout << "is not prime.\n";
}
{ // wait_for
auto is_prime = [](int x) {
for (int i = 2; i < x; ++i) if (x%i == 0) return false;
return true;
};
// call function asynchronously:
std::future<bool> fut = std::async(is_prime, 700020007);
// 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) // 可能多次調(diào)用std::future::wait_for函數(shù)
std::cout << '.';
bool x = fut.get(); // retrieve return value
std::cout << "\n700020007 " << (x ? "is" : "is not") << " prime.\n";
}
return 0;
}
///////////////////////////////////////////////////////////
// reference: https://en.cppreference.com/w/cpp/thread/future
int test_future_2()
{
// future from a packaged_task
std::packaged_task<int()> task([] { return 7; }); // wrap the function
std::future<int> f1 = task.get_future(); // get a future
std::thread t(std::move(task)); // launch on a thread
// future from an async()
std::future<int> f2 = std::async(std::launch::async, [] { return 8; });
#ifdef _MSC_VER
// future from a promise
std::promise<int> p;
std::future<int> f3 = p.get_future();
std::thread([&p] { p.set_value_at_thread_exit(9); }).detach(); // gcc 4.9 don't support this function
#endif
std::cout << "Waiting..." << std::flush;
f1.wait();
f2.wait();
#ifdef _MSC_VER
f3.wait();
#endif
std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' '
#ifdef _MSC_VER
<< f3.get()
#endif
<< '\n';
t.join();
return 0;
}
///////////////////////////////////////////////////////////
// reference: https://thispointer.com/c11-multithreading-part-8-stdfuture-stdpromise-and-returning-values-from-thread/
void initiazer(std::promise<int> * promObj)
{
std::cout << "Inside Thread" << std::endl;
promObj->set_value(35);
}
int test_future_3()
{
std::promise<int> promiseObj;
std::future<int> futureObj = promiseObj.get_future();
std::thread th(initiazer, &promiseObj);
std::cout << "value: " << futureObj.get() << std::endl;
th.join();
// If std::promise object is destroyed before setting the value the calling get() function on associated std::future object will throw exception.
// A part from this, if you want your thread to return multiple values at different point of time then
// just pass multiple std::promise objects in thread and fetch multiple return values from thier associated multiple std::future objects.
return 0;
}
} // namespace future_
GitHub:https://github.com/fengbingchun/Messy_Test
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++ 遞歸遍歷文件并計(jì)算MD5的實(shí)例代碼
在本篇文章里小編給大家整理的是一篇關(guān)于C++ 遞歸遍歷文件并計(jì)算MD5的實(shí)例代碼,有興趣的朋友們可以學(xué)習(xí)參考下。2021-07-07
C語(yǔ)言開發(fā)實(shí)現(xiàn)通訊錄管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言開發(fā)實(shí)現(xiàn)通訊錄管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
C語(yǔ)言實(shí)現(xiàn)memcpy函數(shù)的使用示例
在C語(yǔ)言中,我們可以自己實(shí)現(xiàn) memcpy 函數(shù)來(lái)實(shí)現(xiàn)內(nèi)存數(shù)據(jù)的拷貝操作,本文就來(lái)介紹一下C語(yǔ)言實(shí)現(xiàn)memcpy函數(shù)的使用示例,感興趣的可以了解一下2023-09-09
C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的五子棋小游戲
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的五子棋小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
C++實(shí)現(xiàn)LeetCode(95.獨(dú)一無(wú)二的二叉搜索樹之二)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(95.獨(dú)一無(wú)二的二叉搜索樹之二),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C++實(shí)現(xiàn)分?jǐn)?shù)計(jì)算器
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)分?jǐn)?shù)計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
C++實(shí)現(xiàn)LeetCode(53.最大子數(shù)組)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(53.最大子數(shù)組),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C語(yǔ)言矩陣連乘 (動(dòng)態(tài)規(guī)劃)詳解
這篇文章主要介紹了C語(yǔ)言矩陣連乘 (動(dòng)態(tài)規(guī)劃)詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05

