如何在C++11中使用std::future

本篇文章給大家分享的是有關(guān)如何在C++11中使用std::future,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作與策劃設(shè)計(jì),大興安嶺網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:大興安嶺等地區(qū)。大興安嶺做網(wǎng)站價(jià)格咨詢:13518219792

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)來構(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),因此它是無效的,但是可以通過移動(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ì)用法見下面的測試代碼,下面是從其他文章中copy的測試代碼,部分作了調(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ì)象將變得無效
 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_

以上就是如何在C++11中使用std::future,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

當(dāng)前題目:如何在C++11中使用std::future
轉(zhuǎn)載源于:http://muchs.cn/article26/gpjojg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、網(wǎng)站收錄網(wǎng)站設(shè)計(jì)公司、網(wǎng)站建設(shè)、面包屑導(dǎo)航、云服務(wù)器

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)