std::future 在这个CppCon 演示文稿中被批评为速度慢。您可以通过使用此仅标头库完全避免 std::async 和 std:future 。您可以异步运行任意数量的函数并将结果作为元组获取。也可以正常捕获异常。
这是一个例子:
#include <iostream>
#include "Lazy.h"
template <class T>
T foo(T x) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return x + 10.5;
}
int main() {
int input = 54;
try {
auto [i, d, c] = Lazy::runParallel(
[&](){ return foo(int(input)); },
[&](){ return foo(double(input)); },
[&](){ return foo(char(input)); } );
std::cout << "foo(int) = " << i << ", foo(double) = " << d << ", foo(char) = " << c << '\n';
}
catch (...) {
// Deal with the exception here
}
}
/* Output:
foo(int) = 64, foo(double) = 64.5, foo(char) = @
*/