Welcome to our deep dive into std::future and std::promise! These powerful tools in C++11 allow you to write asynchronous code, making your programs more efficient and responsive. Let's explore them together!
Asynchronous programming is a technique that allows you to execute multiple tasks concurrently. In C++11, we have std::future and std::promise to help with this.
Let's start by understanding the basic usage.
Here's a simple example of using std::future and std::promise:
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int asyncFunction(int input) {
std::this_thread::sleep_for(std::chrono::seconds(3));
return input * 2;
}
int main() {
std::promise<int> promiseObj;
auto futureObj = promiseObj.get_future();
std::thread threadObj(asyncFunction, 5);
promiseObj.set_value(10); // Set the value if you want to bypass the asyncFunction
threadObj.join();
int result = futureObj.get();
std::cout << "Result: " << result << std::endl;
return 0;
}In this example, we create a promise, get its future, and start a thread that executes the asyncFunction. We can also manually set a value for the promise if we want to bypass the asynchronous function. Once the thread finishes, we get the result from the future.
C++20 introduced async and await keywords to simplify asynchronous programming. Here's an example using them:
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
int asyncFunction(int input) {
std::this_thread::sleep_for(std::chrono::seconds(3));
return input * 2;
}
int main() {
auto asyncResult = std::async(std::launch::async, asyncFunction, 5);
auto result = asyncResult.get();
std::cout << "Result: " << result << std::endl;
return 0;
}In this example, we use std::async to start the asynchronous function. The asyncResult is a std::future that we can wait for and get the result.
Both std::promise and std::future support exception handling. If an exception is thrown in the asynchronous function, it will be propagated to the future.
#include <iostream>
#include <future>
#include <stdexcept>
#include <thread>
#include <chrono>
void asyncFunction(std::promise<void> promise) {
throw std::runtime_error("Exception in asyncFunction");
}
int main() {
std::promise<void> promiseObj;
std::future<void> futureObj = promiseObj.get_future();
std::thread threadObj(asyncFunction, std::move(promiseObj));
try {
futureObj.get();
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
threadObj.join();
return 0;
}In this example, an exception is thrown in the asyncFunction. The exception is propagated to the future and caught in the main function.
Which C++ standard introduced `std::async` and `std::await`?
Keep learning and practicing! š