3 ms·
It's interesting that there is async/await in C++ now. I don't like the idea that it is thread based - part of what makes async/await fast in other languages i
by andrewstuart 4y ago
It's interesting that there is async/await in C++ now. I don't like the idea that it is thread based - part of what makes async/await fast in other languages is that it is NOT thread based.
Here's an example from ChatGPT (not checked for correctness)
int main() {
// Define an asynchronous task that returns a string
auto my_task = []() -> std::string {
return "Hello, world!";
};
// Call the task using async and wait for the result
auto future_result = std::async(std::launch::async, my_task);
std::string result = future_result.get();
// Print the result
std::cout << result << std::endl;
return 0;
}
"In this example, we define an asynchronous task using a lambda function. The lambda function returns a string, but since it is an asynchronous task, it is executed in a separate thread.
Next, we use the std::async function to execute the task asynchronously. The std::async function takes two arguments: the launch policy and the function to execute. In this example, we use the std::launch::async policy to launch the function in a new thread. The std::async function returns a std::future object, which represents the result of the asynchronous operation.
Finally, we use the get method of the std::future object to wait for the result of the asynchronous operation. The get method blocks the calling thread until the asynchronous operation is complete and the result is available."