How is the “async” function used in C++?
In C++, the std::async function is used to create an asynchronous task and returns a std::future object, which can be used to retrieve the result of the asynchronous task.
The usage of the std::async function is as follows:
#include <iostream>
#include <future>
int foo(int x) {
return x * x;
}
int main() {
// 创建一个异步任务
std::future<int> fut = std::async(foo, 10);
// 等待异步任务完成并获取结果
int result = fut.get();
std::cout << "Result: " << result << std::endl;
return 0;
}
In the example above, the std::async function creates an asynchronous task that calls the foo function with the parameter 10. The result of the asynchronous task can be obtained through the std::future object fut, which ultimately outputs the result as 100.
It is important to note that the behavior of the std::async function depends on the parameters passed to it. By default, std::async will execute asynchronous tasks in a background thread, but you can also use the std::launch::deferred parameter to defer task execution until the get function of std::future is called, or the std::launch::async parameter to immediately execute the task when calling std::async.