/*std::future is a C++11 class that represents a value or an exception that will be
available in the future. It can be used to retrieve the result of a function
executed in a separate thread of execution.
One way to wait for the result of a std::future is to use the std::future::wait()
member function. wait() blocks the calling thread until the result is available.
Here is an example of using std::async to launch a function in a separate thread
and waiting for the result using std::future::wait():*/
#include <iostream>
#include <future>
#include <chrono>
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
int long_running_task() {
std::cout << "Performing long-running task..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "Task complete." << std::endl;
return 42;
}
int main() {
std::cout << "Starting long-running task..." << std::endl;
std::future<int> result = std::async(long_running_task);
std::cout << "Doing other work while the task runs..." << std::endl;
// ...
std::cout << "Waiting for result of long-running task..." << std::endl;
result.wait();
std::cout << "Retrieving result of long-running task..." << std::endl;
int task_result = result.get();
std::cout << "Result of long-running task: " << task_result << std::endl;
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: