Sobes.tech
Junior — Middle

Can you explain the purpose and operation of the std::async function in C++?

sobes.tech AI

Answer from AI

The std::async function in C++ is used to launch a task asynchronously, that is, in a separate thread, allowing operations to run in parallel with the main thread.

It returns a std::future object, which can be used to obtain the result of the task when it is ready.

Example of usage:

#include <iostream>
#include <future>

int compute() {
    // Long operation
    return 42;
}

int main() {
    std::future<int> result = std::async(std::launch::async, compute);
    // Can perform other tasks
    std::cout << "Result: " << result.get() << std::endl;
    return 0;
}

In this example, the compute function runs in a separate thread, while the main thread can continue working until the result is needed.