认识 std::async: 用同步的语法却做着异步的事情!
#include <future>
#include <iostream>
#include <string>
#include <functional>
void run(std::string str)
{
if (str.compare("a1") == 0)
{
char pause = getchar(); // 获取键盘输入, 这里起到阻塞线程的作用,方便观察调试结果
}
std::cout << str << std::endl;
}
void Print(std::function< void(std::string)> funcPtr)
{
while(1){
auto a1 = std::async(std::launch::async, funcPtr, "a1");
auto a2 = std::async(std::launch::async, funcPtr, "a2");
auto a3 = std::async(std::launch::async, funcPtr, "a3");
auto a4 = std::async(std::launch::async, funcPtr, "a4");
auto a5 = std::async(std::launch::async, funcPtr, "a5");
auto a6 = std::async(std::launch::async, funcPtr, "a6");
std::cout << std::endl << " ================================================== " << std::endl << std::endl;
// 这里面的代码执行是乱序,还有可能执行多次
}
}
int main()
{
Print(run);
return 0;
}
上面的代码适合调试,再看同步递归版本和异步递归版本的斐波那契数列求和:
#include <iostream>
#include <future>
long long feibonahi(int n)
{
if (n <= 2)
{
return 1;
}
else
{
return feibonahi(n - 1) + feibonahi(n - 2);
}
}
int fib(int n) {
if (n <= 1) {
return n;
}
auto future1 = std::async(std::launch::async, fib, n-1);
auto future2 = std::async(std::launch::async, fib, n-2);
int f1 = future1.get();
// std::cout << "future1 = " << f1 << std::endl;
int f2 = future2.get();
/*
std::cout << f1 + f2 << " f1 = " << f1 << " f2 = " << f2 << std::endl;
打印的结果有点乱,这里有点难理解,mark一下
*/
//return future1.get() + future2.get();
return f1 + f2;
}
int main(int argc, char **argv) {
int num = 10;
std::cout << " " << feibonahi(10) << std::endl << std::endl;
std::promise<int> p; // p是起到线程间传递值得作用,这里不容易看出,可以将p通过std::ref(p)的方式传递线程的run方法中去,run方法: void run(std::promise<int> &p) {p.set_value(result);}
std::future<int> f = p.get_future();
// 开启一个线程异步计算斐波那契数列并将结果存入promise中
std::thread t([&]{
int result = fib(num);
p.set_value(result); // p.setvalue触发 f.get()
});
t.detach();
/*
主线程等待结果并打印
*/
std::cout << "The " << num << "th fibonacci number is: " << f.get() << std::endl; // f.get() 这里有阻塞线程的效果
return 0;
}
上的的异步递归版本也能求出 斐波那契数列 的结果。
个人理解:
std::async函数是异步执行的,相当于任务提交到线程池中执行,线程池中的线程数量有限, 所以多个std::async的执行顺序和执行次数不确定,可能会出现乱序情况和多次执行的情况(从调试的打印信息可以看出)。
此外,std::async函数的执行结果也不确定何时返回,需要通过调用std::future对象的get()方法来获取执行结果,
如果在get()方法调用之前任务没有完成,get()方法会阻塞当前线程直到任务完成。
因此,如果多个std::async函数的执行顺序很重要,可以使用std::future对象的wait()或者wait_for()方法来等待其它任务完成后再获取结果。