std::async
用于创建异步任务,std::packaged_task
则将一个可调用对象(包括函数、函数对象、lambda表达式、std::bind表达式、std::function对象)进行包装,以便该任务能被异步调用(即在其他线程中调用)。二者均可通过std::future
对象返回执行结果。二者使用的一个主要差别是:std::packaged_task
需要等待执行结果返回,而std::async
不必。下面给出一个体现二者差异的示例程序:
#include <functional>
#include <future>
#include <iostream>
int main() {
//! sleeps for one second and returns 1
auto sleep = []() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 1;
};
//
// Case 1: packaged_task
//
std::packaged_task<int()> task(sleep);
auto f1 = task.get_future();
auto start = std::chrono::high_resolution_clock::now();
task(); // invoke the function
auto stop = std::chrono::high_resolution_clock::now();
// You have to wait until task returns. Since task calls sleep
// you will have to wait at least 1 second.
std::cout << "You can see this after "
<< std::chrono::duration<double>(stop - start).count()
<< " second\n";
// However, f.get() will be available, since task has already finished.
std::cout << f1.get() << std::endl;
//
// Case 2: async
//
auto f2 = std::async(std::launch::async, sleep);
std::cout << "You can see this immediately!\n";
// However, the value of the future will be available after sleep has finished
// so f.get() can block up to 1 second.
start = std::chrono::high_resolution_clock::now();
auto result = f2.get();
stop = std::chrono::high_resolution_clock::now();
// you will have to wait at least 1 second.
std::cout << "You can see " << result << " after "
<< std::chrono::duration<double>(stop - start).count()
<< " second\n";
return 0;
}
编译指令如下:
g++ -g -Wall -std=c++11 *.cpp -o test
在我机器上的运行结果如下:
You can see this after 1.00027 second
1
You can see this immediately!
You can see 1 after 1.00061 second