C++11中std::future的使用
C++11中的std::future是一個模板類。std::future提供了一種用于訪問異步操作結(jié)果的機制。std::future所引用的共享狀態(tài)不能與任何其它異步返回的對象共享(與std::shared_future相反)( std::future references shared state that is not shared with any other asynchronous return objects (as opposed to std::shared_future))。一個future是一個對象,它可以從某個提供者的對象或函數(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對象,可以通過調(diào)用以下函數(shù)(provider)來構(gòu)造future對象:std::async、std::promise::get_future、std::packaged_task::get_future。future對象僅在它們是有效時才有用。
std::aysnc介紹參考:https://blog.csdn.net/fengbingchun/article/details/104133494
std::promise介紹參考:https://blog.csdn.net/fengbingchun/article/details/104124174
std::packaged_task介紹參考:https://blog.csdn.net/fengbingchun/article/details/104127352
模板類std::future成員函數(shù)包括:
1. 構(gòu)造函數(shù):(1).不帶參數(shù)的默認構(gòu)造函數(shù),此對象沒有共享狀態(tài),因此它是無效的,但是可以通過移動賦值的方式將一個有效的future值賦值給它;(2).禁用拷貝構(gòu)造;(3).支持移動構(gòu)造。
2. 析構(gòu)函數(shù):銷毀future對象,它是異常安全的。
3. get函數(shù):(1).當(dāng)共享狀態(tài)就緒時,返回存儲在共享狀態(tài)中的值(或拋出異常)。(2).如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒。(3).當(dāng)共享狀態(tài)就緒后,則該函數(shù)將取消阻塞并返回(或拋出)釋放其共享狀態(tài),這使得future對象不再有效,因此對于每一個future共享狀態(tài),該函數(shù)最多應(yīng)被調(diào)用一次。(4).std::future<void>::get()不返回任何值,但仍等待共享狀態(tài)就緒并釋放它。(5).共享狀態(tài)是作為原子操作(atomic operation)被訪問。
4. operator=:(1).禁用拷貝賦值。(2).支持移動賦值:如果在調(diào)用之前,此對象是有效的(即它已經(jīng)訪問共享狀態(tài)),則將其與先前已關(guān)聯(lián)的共享狀態(tài)解除關(guān)聯(lián)。如果它是與先前共享狀態(tài)關(guān)聯(lián)的唯一對象,則先前的共享狀態(tài)也會被銷毀。
5. share函數(shù):獲取共享的future,返回一個std::shared_future對象,該對象獲取future對象的共享狀態(tài)。future對象將不再有效。
6. valid函數(shù):檢查共享狀態(tài)的有效性,返回當(dāng)前的future對象是否與共享狀態(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)在指定的時間內(nèi)(time span)準備就緒。(2). 如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒或已達到設(shè)置的時間。(3).此函數(shù)的返回值類型為枚舉類future_status。此枚舉類有三種label:ready:共享狀態(tài)已就緒;timeout:在指定的時間內(nèi)未就緒;deferred:共享狀態(tài)包含了一個延遲函數(shù)(deferred function)。
9. wait_until函數(shù):(1). 等待共享狀態(tài)在指定的時間點(time point)準備就緒。(2). 如果共享狀態(tài)尚未就緒(即提供者尚未設(shè)置其值或異常),則該函數(shù)將阻塞調(diào)用的線程直到就緒或已達到指定的時間點。(3).此函數(shù)的返回值類型為枚舉類future_status。
詳細用法見下面的測試代碼,下面是從其他文章中copy的測試代碼,部分作了調(diào)整,詳細內(nèi)容介紹可以參考對應(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-constructedstd::future<int> bar = std::async(get_value); // move-constructedint x = bar.get();std::cout << "value: " << x << '\n'; // 10//int x2 = bar.get(); // crash, 對于每個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
}{ // sharestd::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對象將變得無效std::cout << "fut valid: " << fut.valid() << '\n';// 0// shared futures can be accessed multiple times:std::cout << "value: " << shfut.get() << '\n'; // 10std::cout << "its double: " << shfut.get() * 2 << '\n'; // 20, 對于std::shared_future對象,get函數(shù)可以被多次訪問
}{ // validstd::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 validif (bar.valid()) std::cout << "bar's value: " << bar.get() << '\n'; // 10else std::cout << "bar is not valid\n";
}{ // waitauto 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 returnsstd::cout << "is prime.\n";elsestd::cout << "is not prime.\n";
}{ // wait_forauto 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 valuestd::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_taskstd::packaged_task<int()> task([] { return 7; }); // wrap the functionstd::future<int> f1 = task.get_future(); // get a futurestd::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 promisestd::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
#endifstd::cout << "Waiting..." << std::flush;f1.wait();f2.wait();
#ifdef _MSC_VERf3.wait();
#endifstd::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
總結(jié)
以上是生活随笔為你收集整理的C++11中std::future的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++中关键字volatile和muta
- 下一篇: C++11中std::shared_fu