How it works...

In this recipe, we will learn how to manually use a C++ promise and future to provide a function that is executed in parallel with an argument, as well as get the function's return value. To start, let's demonstrate how this is done in its most simplistic form, with the following code:

#include <thread>
#include <iostream>
#include <future>

void foo(std::promise<int> promise)
{
promise.set_value(42);
}

int main(void)
{
std::promise<int> promise;
auto future = promise.get_future();

std::thread t{foo, std::move(promise)};
t.join();

std::cout << "The answer is: " << future.get() << ' ';

return 0;
}

The preceding example results in the following when executed:

As you can see in the preceding code, the C++ promise is an argument to the function that is threaded. The thread returns its value by setting the promise argument, which, in turn, sets a C++ future that the user can get from the promise argument it provides to the thread. It should be noted that we use std::move() to prevent the promise argument from being copied (which the compiler will prohibit as the C++ promise is a move-only class). Finally, we use the get() function to get the result of the thread, the same way you would get the result of a thread executed using std::async.

One of the benefits of using promise and future manually is that you can get the result of the thread before it completes, allowing the thread to continue to do work. For example, take a look at the following:

#include <thread>
#include <iostream>
#include <future>

void foo(std::promise<int> promise)
{
promise.set_value(42);
while (true);
}

int main(void)
{
std::promise<int> promise;
auto future = promise.get_future();

std::thread t{foo, std::move(promise)};

future.wait();
std::cout << "The answer is: " << future.get() << ' ';

t.join();

// Never reached
return 0;
}

This results in the following when executed:

In the preceding example, we created the same thread, but we looped forever in the thread, meaning the thread will never return. We then created the thread the same way, but outputted the result of the C++ future as soon as it was ready, which we can determine using the wait() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset