C++11 使用异步编程std::async和std::future
先说明一点: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::future、std::promise、std::packaged_task
二、std::future说明
四、std::packaged_task用法
std::packaged_task的作用就是提供一个不同线程之间的数据同步机制,它可以存储一个函数操作,并将其返回值传递给对应的future, 而这个future在另外一个线程中也可以安全的访问到这个值。
示例代码:
https://www.cnblogs.com/moodlxs/p/10111601.html
#if 0
//https://www.cnblogs.com/moodlxs/p/10111601.html
// 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;
}
#elif 1
#include <iostream>
#include <future>
#include <thread>
#include <string>
class myClass
{
public:
bool test(int x) {
std::cout << "x: " << x << std::endl;
return true;
}
};
int main()
{
//myClass的一个实例
myClass obj;
//利用std::bind绑定类的成员函数
auto func = std::bind(&myClass::test, obj, 1);
//构造future对象
std::future<bool> fut = std::async(std::launch::async, func);
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 rtn = fut.get();
std::cout << "final result: " << rtn << std::endl;
return 0;
}
#elif 0
// 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;
}
#elif 0
#include <iostream>
#include <future>
#include <thread>
#include <string>
int fun(std::string x2) {
/*x++;
x *= 10;*/
int x = 0;
std::cout << std::this_thread::get_id() << std::endl;
return x;
}
int main()
{
// std::launch::deferred 当执行到fu.get才开始创建线程
// std::future<int> fu = std::async(std::launch::deferred, fun, 1);
std::future<int> fu = std::async(std::launch::async, fun, "ni");
std::cout << fu.get() << std::endl;
std::cout << std::this_thread::get_id() << std::endl;
return 0;
}
#elif 0
#include <iostream>
#include <future>
#include <thread>
int fun(int x) {
x++;
x *= 10;
std::cout << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
return x;
}
int main()
{
std::packaged_task<int(int)> pt(fun); // 将函数打包起来
std::future<int> fu = pt.get_future(); // 并将结果返回给future
std::thread t(std::ref(pt), 1);
std::cout << fu.get() << std::endl;
std::cout << std::this_thread::get_id() << std::endl;
t.join();
return 0;
}
#endif