先來個小插曲,百度翻譯,你夠了:?

**std::future**
設想這樣的情況,你希望一個線程做一些事情,然后返回你一個結果。同時,你在做一些其他的工作,該工作也許會也許不會花費你一點時間。你希望在某個特定的時間獲取那個線程的結果。?
在win32中,你可以這樣?
用CreateThread啟動線程?
在線程里,啟動任務,當準備完畢后發送一個事件(event),并把結果放在全局變量里。?
在主函數里(main)做其它的事情,然后在你想要結果的地方,調用WaitForSingleObject?
在c++11,這個可以輕松被std::future實現,然后返回任何類型,因為它是一個模板。
std::future 究竟是什么呢?簡單地說,std::future 可以用來獲取異步任務的結果,因此可以把它當成一種簡單的線程間同步的手段。
讓我們考慮一個簡單的事兒:用線程計算一些值:
~~~
std::thread t([]() { auto res = perform_long_computation(); });
~~~
std::thread在之前的博客中已經介紹過了。我們還可以更高效嗎?
~~~
MyResult sharedRes;
std::thread t([&]() { sharedRes = perform_long_computation(); });
~~~
這個時候,我們應該知道thread什么時候執行結束,這里有一個很簡單的方式
~~~
auto result = std::async([]() { return perform_long_computation(); });
MyResult finalResult = result.get();
~~~
上訴代碼很簡潔明了吧,我們需要弄清其原理。?
英文描述可能更加確切:?
std::future holds a shared state?
std::async allow us to run the code asynchronously.?
因此,有了這樣的代碼:
~~~
std::future<MyResult> result = std::async([]() { return perform_long_computation(); });
MyResult finalResult = result.get();
~~~
上一段完整的代碼:
~~~
// 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;
}
~~~
輸出:?
checking, please wait……………………?
444444443 is prime.
**std::async**?
為什么要用std::async代替線程的創建
std::async是為了讓用戶的少費點腦子的,它讓這三個對象默契的工作。大概的工作過程是這樣的:std::async先將異步操作用std::packaged_task包裝起來,然后將異步操作的結果放到std::promise中,這個過程就是創造未來的過程。外面再通過future.get/wait來獲取這個未來的結果,怎么樣,std::async真的是來幫忙的吧,你不用再想到底該怎么用std::future、std::promise和std::packaged_task了,std::async已經幫你搞定一切了!
現在來看看std::async的原型
~~~
async(std::launch::async | std::launch::deferred, f, args...)
~~~
第一個參數是線程的創建策略,有兩種策略,默認的策略是立即創建線程:?
std::launch::async:在調用async就開始創建線程。?
std::launch::deferred:延遲加載方式創建線程。調用async時不創建線程,直到調用了future的get或者wait時才創建線程。?
第二個參數是線程函數,第三個參數是線程函數的參數。
~~~
std::future<int> future = std::async(std::launch::async, [](){
std::this_thread::sleep_for(std::chrono::seconds(3));
return 8;
});
std::cout << "waiting...\n";
std::future_status status;
do {
status = future.wait_for(std::chrono::seconds(1));
if (status == std::future_status::deferred) {
std::cout << "deferred\n";
} else if (status == std::future_status::timeout) {
std::cout << "timeout\n";
} else if (status == std::future_status::ready) {
std::cout << "ready!\n";
}
} while (status != std::future_status::ready);
std::cout << "result is " << future.get() << '\n';
~~~
可能的結果:?
waiting…?
timeout?
timeout?
ready!?
result is 8
這里寫代碼片?
“`
- 前言
- 吐血整理C++11新特性
- C++11新特性之std::function
- c++11特性之正則表達式
- c++11特性之Lambda表達式
- c++11特性之override和final關鍵字
- c++11特性之std::thread--初識
- c++11特性之std::thread--初識二
- c++11特性之initializer_list
- c++11特性之std::thread--進階
- c++11特性之std::thread--進階二
- C++11新特性之 CALLBACKS
- C++11新特性之 std::array container
- C++11新特性之 nullptr
- C++11新特性之 rvalue Reference(右值引用)
- C++11新特性之 Move semantics(移動語義)
- C++11新特性之 default and delete specifiers
- C++11新特性之 Static assertions 和constructor delegation
- 開始使用C++11的幾個理由
- C++11新特性之 std::future and std::async