C++ Standard Library<future>
C++11 introduced<future>The header file provides a mechanism for asynchronous programming, allowing the program to continue executing other tasks while waiting for an operation to complete.<future>The library is part of concurrent programming in the C++ standard library, allowing programmers to handle asynchronous operations in a more concise and safe way.
<future>The library defines several key types:
std::future: Represents the result of an asynchronous operation, allowing you to query the operation's status, retrieve the result, or wait for the operation to complete.std::promise: used withstd::futurepaired, used to set the result of asynchronous operations.std::packaged_task: Wraps a function or callable object so that it can be executed as an asynchronous task.
std::promise
std::promiseUsed to set the result of asynchronous operations. It is paired withstd::futureused in pairs.
Example
#include <future>
int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future();
// Set the result in another thread
std::thread t([prom]() {
prom.set_value(10);
});
// Wait for the result
std::cout << "Future value: " << fut.get() << std::endl;
t.join();
return 0;
}
Output result:
Future value: 10
std::packaged_task
std::packaged_taskWraps a function or callable object so that it can be executed as an asynchronous task.
Example
#include <future>
#include <cmath>
int compute_square_root(double x) {
return std::sqrt(x);
}
int main() {
std::packaged_task<double(double)> task(compute_square_root);
std::future<double> result = task.get_future();
std::thread th(std::move(task), 9.0);
std::cout << "Result: " << result.get() << std::endl;
th.join();
return 0;
}
Output result:
Result: 3
std::async
std::asyncIs a convenient function for launching asynchronous tasks. It can immediately return astd::futureObject.
Example
#include <future>
int main() {
std::future<int> fut = std::async(std::launch::async, [](int x) {
return x * x;
}, 5);
std::cout << "Result: " << fut.get() << std::endl;
return 0;
}
Output result:
Result: 25
Exception Handling
When an asynchronous operation throws an exception,std::futureWill catch this exception, and can by calling.get()method to rethrow it.
Example
#include <future>
void throw_exception() {
throw std::runtime_error("Exception thrown");
}
int main() {
std::future<void> fut = std::async(throw_exception);
try {
fut.get();
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
Output result:
Caught exception: Exception thrown
<future>The library provides C++ programmers with a simple and powerful way of asynchronous programming. By usingstd::promise、std::packaged_taskandstd::async, we can easily implement concurrent and asynchronous operations in C++ programs. Meanwhile, the exception handling mechanism also ensures the robustness of the program.