std::async and std::future


Using std::future and std::async is a simple way to implement multithreading in c++. The syntax looks somewhat complicated but it is a convenient way to implement without worrying about threads.

whiteboard example for using many threads to load and write textures

I understand that all this syntax looks pretty crazy, especially if you have zero experience with future or async. Lets go through it line by line to maximize out understanding.


This reduced my overall runtime from 370,000ms to 70,000ms.

textureCount: just refers to subfolders in the textures folder.

textureFiles: are the different textures in the texture subfolders.

straight from the cppreference website:

"std::future provides a mechanism to access the result of asynchronous operations"

In our case a asynchronous operation is just a function we want to run on a thread, separate from the main thread.

std::async is a function provided by the <future> header, it literally creates a future and returns it. So that auto evaluated to std::future<void>.

std::async takes in a 2 parameters, the first parameter just informs how the second parameter behaves. the second parameter is a function pointer.

Now you can clearly see, that the function has 4 parameters not 2, that is because the parameters following the second parameter, are actually the parameters for the 2 second parameter.

this is the function being passed into the std::async. It takes in 2 parameters which are following the function pointer in the std::async function. This function calls the parametrized constructor of texture, then calls the write_png function.


side note: a function pointer is just a function with out the parenthesis at the end ie-> test() is a function, test is a function pointer, or functor.

think of a future as a literal thread, and you are loading all the data on it you want to run.


std::launch::async effects how the function is called. the other option is std::launch::deferred, which would put the threads in a que to run one right after the other, which would not save anytime and is effectively the same as in order.

the get() function in the future header that returns the result of the thread, if the function returned something this is where we could get that result. Would be useful if doing many calculations for a custom physics engine. In this case we just make sure the texture is done writing.

that is why the future is type void, future<void>, because it returns nothing.