#include <iostream>
#include <future>
#include <thread>
#include <chrono>
using namespace std;
/*
std::future可以从异步任务中获取结果,一般与std::async配合使用,std::async用于创建异步任务,实际上就是创建一个线程执行相应任务。
*/
int test_fun(int x)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
return x+100;
}
void print_int (std::future<int>& fut)
{
int x = fut.get();
std::cout << "value: " << x << '\n';
}
int main()
{
//std::future只能用于单线程中调用 ,多线程调用使用std::share_future();
//async会创建线程执行test_fun,任务创建之后,std::async立即返回一个std::future对象
/*async原型为
template<class Fn, class... Args>
future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&...args);
launch policy,如果我们不指定策略,则相当于(3)
(1)、std::launch::async 传递的可调用对象异步执行;
(2)、std::launch::deferred 传递的可调用对象同步执行,选择同步执行策略,只有当调用get函数时,同步调用才真正执行
(3)、std::launch::async | std::launch::deferred 可以异步或是同步,取决于操作系统,我们无法控制;
*/
std::future<int> fut = std::async(test_fun, 1011);
std::cout << "please wait"<<endl;
//std::future::get如果调用过程中,任务尚未完成,则主线程阻塞至任务完成
//std::future::wait_for等待结果返回,可设置超时时间,如果在超时时间之内任务完成,则返回std::future_status::ready状态;如果在超时时间之内任务尚未完成,则返回std::future_status::timeout状态
//std::future::wait 等待结果变得可用
//std::future::wait_until 等到某时间段未完成,则返回
std::chrono::seconds span(3);
if(fut.wait_for(span) == std::future_status::ready)
{
cout <<"ready"<<endl;
}
else
{
cout <<"timeout"<<endl;
}
cout<< "result is"<<fut.get() <<endl;
//std::promise提供一个不同线程之间的数据同步机制,它可以存储一个某种类型的值,并将其传递给对应的future, 即使这个future不在同一个线程中也可以安全的访问到这个值
std::promise<int> prom; // create promise
std::future<int> fut2 = prom.get_future(); // engagement with future
std::thread th1 (print_int, std::ref(fut2)); // send future to new thread
prom.set_value(10); // fulfill promise
// (synchronizes with getting the future)
th1.join();
return 0;
}
基于C++11异步编程std::async和std::future
最新推荐文章于 2024-10-10 10:58:41 发布