先说明一点:std::asyanc是std::future的高级封装, 一般我们不会直接使用std::futrue,而是使用对std::future的高级封装std::async。 下面分别说一下。
一、std::async基本用法
std::future可以从异步任务中获取结果,一般与std::async配合使用,std::async用于创建异步任务,实际上就是创建一个线程执行相应任务。
std::async就是异步编程的高级封装,封装了std::future的操作,基本上可以代替std::thread 的所有事情。
std::async的操作,其实相当于封装了std::promise、std::packaged_task加上std::thread。
使用代码如下:
#include <future>
#include <iostream>
#include <stout/stringify.hpp>
bool is_prime(int x)
{
for (int i=0; i<x; i++)
{
if (x % i == 0)
return false;
}
return true;
}
int main()
{
std::future<bool> fut = std::async(is_prime, 700020007);
std::cout << "please wait";
std::chrono::milliseconds span(100);
while (fut.wait_for(span) != std::future_status::ready)
std::cout << ".";
std::cout << std::endl;
bool ret = fut.get();
std::cout << "final result: " << stringify(ret) << std::endl;
return 0;
}
std::async会首先创建线程执行is_prime(700020007), 任务创建之后,std::async立即返回一个std::future对象。
主线程既可使用std::future::get获取结果,如果调用过程中,任务尚未完成,则主线程阻塞至任务完成。
主线程也可使用std::future::wait_for等待结果返回,wait_for可设置超时时间,如果在超时时间之内任务完成,则返回std::future_status::ready状态;如果在超时时间之内任务尚未完成,则返回std::future_status::timeout状态。
std::async提供了std:thread 不能提供的返回值 的功能
还可以选择异步形式:
std::launch::async //开一个新线程执行
std::launch::deferred //目标函数的调用延迟到wait或者get函数才执行 等同于 std::launch::sync
std::launch::async | std::launch::deferred //等同于std::launch::any
std::future<int> _ans = std::async( std::launch::async,calculateBill, 100); //异步执行
std::future<int> _ans = std::async( std::launch::deferred,calculateBill, 100);//等到get 或者wait才执行
上面先说了通用的做法,然后我们了解一下std::future、std::promise、std::packaged_task
二、std::future说明
future对象是std::async、std::promise、std::packaged_task的底层对象,用来传递其他线程中操作的数据结果。
三、std::promise用法
std::promise的作用就是提供一个不同线程之间的数据同步机制,它可以存储一个某种类型的值,并将其传递给对应的future, 即使这个future不在同一个线程中也可以安全的访问到这个值。
示例代码:
// promise example
#include <iostream> // std::cout
#include <functional> // std::ref
#include <thread> // std::thread
#include <future> // std::promise, std::future
void print_int (std::future<int>& fut) {
int x = fut.get();
std::cout << "value: " << x << '\n';
}
int main ()
{
std::promise<int> prom; // create promise
std::future<int> fut = prom.get_future(); // engagement with future
std::thread th1 (print_int, std::ref(fut)); // send future to new thread
prom.set_value (10); // fulfill promise
// (synchronizes with getting the future)
th1.join();
return 0;
}
四、std::packaged_task用法
std::packaged_task的作用就是提供一个不同线程之间的数据同步机制,它可以存储一个函数操作,并将其返回值传递给对应的future, 而这个future在另外一个线程中也可以安全的访问到这个值。
示例代码:
// packaged_task example
#include <iostream> // std::cout
#include <future> // std::packaged_task, std::future
#include <chrono> // std::chrono::seconds
#include <thread> // std::thread, std::this_thread::sleep_for
// count down taking a second for each value:
int countdown (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 << "Lift off!\n";
return from-to;
}
int main ()
{
std::packaged_task<int(int,int)> tsk (countdown); // set up packaged_task
std::future<int> ret = tsk.get_future(); // get future
std::thread th (std::move(tsk),10,0); // spawn thread to count down from 10 to 0
// ...
int value = ret.get(); // wait for the task to finish and get result
std::cout << "The countdown lasted for " << value << " seconds.\n";
th.join();
return 0;
}
Possible Output:
10
9
8
7
6
5
4
3
2
1
Lift off!
The countdown lasted for 10 seconds.
在其他地方看到还有作为队列使用的方式,如下:
typedef std::packaged_task<int(int)> task;
int calculateBill(int base)
{
Sleep(500);
return base * 2;
}
int main(...)
{
std::vector<task> tasks;
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
tasks.push_back(std::move(task(calculateBill)));
int i = 0;
for (auto & task : tasks)
{
task(++i);
std::future<int> ans1 = task.get_future();
cout << ans1.get() << endl;//阻塞会等待结果的返回
}
system("pause");
return 0;
}
还可以并发处理:
int i = 0;
for (auto & task : tasks)
{
std::thread t([&]
{
task(++i);
std::future<int> ans1 = task.get_future();
cout << ans1.get() << endl;
});
t.detach();
}