使用feature特性,可以获得异步执行的效果。如下面的例子
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
int loopType (int from, int to)
{
for (int i = from; i != to; ++i)
{
std::cout << i << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "loop finished!\n";
return from - to;
}
int main(int argc, char* argv[])
{
std::packaged_task<int(int,int)> task(loopType);
std::future<int> ret = task.get_future();
std::thread th(std::move(task), 0, 16);
std::cout << "run...\n";
int value = ret.get(); // 等待任务完成并得到结果.
std::cout << "The loopType lasted for " << value << " seconds.\n";
th.join();
return 0;
}
从下面的运行图可以看出,ret异步获得了线程函数运行结果。