std::async 是 C++11 标准库中引入的一个函数模板,用于启动一个异步任务,并返回一个 std::future 对象,用于获取异步任务的结果。 std::async 提供了一种简单的方式来并行化代码执行,而不需要显式地管理线程的生命周期。
# 1、作用
- 启动异步任务:
std::async 启动一个新的任务,这个任务可以在新线程中并行执行。 - 管理任务结果:
std::async 返回一个 std::future 对象,允许调用者在异步任务完成后获取结果。 - 简化并发编程:与直接使用
std::thread 相比, std::async 简化了并发编程,自动管理线程的创建和销毁。
# 2、参数
- 启动策略:
std::launch::async 或 std::launch::deferred 。 - 可调用对象:函数、lambda 表达式、函数对象、成员函数等。
- 可调用对象的参数:可变数量的参数,用于传递给可调用对象。
# 3、使用
std::async 可以接受多个参数,包括启动策略、可调用对象(如函数、lambda 表达式、函数对象等)和可调用对象的参数。
# 3.1 基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <iostream> #include <future>
int compute() { return 42; }
int main() { std::future<int> result = std::async(compute);
std::cout << "Result: " << result.get() << std::endl;
return 0; }
|
# 3.2 启动策略
std::async 提供了两种启动策略:
std::launch::async :强制在新线程中异步执行任务。std::launch::deferred :延迟执行任务,只有在调用 std::future::get() 或 std::future::wait() 时才执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> #include <future>
int compute() { return 42; }
int main() { std::future<int> async_result = std::async(std::launch::async, compute); std::cout << "Async Result: " << async_result.get() << std::endl;
std::future<int> deferred_result = std::async(std::launch::deferred, compute); std::cout << "Deferred Result: " << deferred_result.get() << std::endl;
return 0; }
|
# 3.3 带参数的任务
std::async 可以启动带参数的任务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <iostream> #include <future>
int add(int a, int b) { return a + b; }
int main() { std::future<int> result = std::async(add, 2, 3);
std::cout << "Result: " << result.get() << std::endl;
return 0; }
|
# 3.4 使用 lambda 表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <iostream> #include <future>
int main() { auto lambda = [](int a, int b) { return a + b; };
std::future<int> result = std::async(lambda, 2, 3);
std::cout << "Result: " << result.get() << std::endl;
return 0; }
|
# 3.5 使用成员函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <iostream> #include <future>
class Calculator { public: int multiply(int a, int b) { return a * b; } };
int main() { Calculator calc;
std::future<int> result = std::async(&Calculator::multiply, &calc, 2, 3);
std::cout << "Result: " << result.get() << std::endl;
return 0; }
|
同样地,在传递成员函数时,需要额外传递对象。
# 4、 std::async 与 std::thread 的比较
- 管理线程:
std::async 自动管理线程的生命周期,而 std::thread 需要手动管理。 - 返回结果:
std::async 返回一个 std::future 对象,用于获取异步结果,而 std::thread 不提供此功能。 - 启动策略:
std::async 可以选择延迟启动策略,而 std::thread 总是在创建时启动。
总之, std::async 是一个强大且灵活的工具,用于简化并发编程和任务管理。
通过使用 std::async ,程序员可以更容易地实现异步操作,提高程序的性能和响应速度。