C++11's std::future and std::async provide a simple mechanism for running functions in separate threads and retrieving their results asynchronously. std::async launches a function in a new thread and returns a future object that holds the result; calling .get() on the future retrieves the computed value. To achieve effective parallelization, pass function parameters as copies and return copyable values, avoiding shared data that would require manual synchronization. This approach allows multiple independent tasks to run concurrently, utilizing multiple CPU cores simultaneously.
std::future Quick-Start: Async C++ for Parallelism
Added:hello and welcome to episode 9 of C++ weekly I'm your host Jason Turner once a week I will pick some topic of interest in C++ and dig into it with some live coding in this episode I'm going to show a quick start of C++ Futures back in 2008 I wrote a series of articles about multi-threaded C++ programming and they're still some of the most popular articles on my website however these articles are largely lowlevel compared to what is possible today with the C++ 11 and C++ 14 standard libraries so let's start here with uh hypothetical example let's say that we want to play around with the C++ random number generation facilities to see what kind of distributions we get so we're going to create a function let's have it return a set of integers because we want to see a sorted set of values that have been returned by the random number facility so we will call it make sorted random and we want to take some parameter that tells us how many values we want to generate so in here we have our return value which is a set of integers and we are going to use a random device and the mercine Twister if I'm pronouncing that right generator that is seated with our random device and I am using the example here from CBP reference to get us started so we want to create a uniform int distribution and uniform it distribution of let's say from one to the number of elements that have been passed in so you know let's say from 0 to the number of elements minus one and for this to work we need to include our random header and now we need some way of using this uniform int distribution to populate our set so we're going to use use the generate in algorithm which I have the documentation up for here so generate in can take an output iterator a size and the generator that we want to call so we are going to let's see pass it a inserter for our rville that inserts at the end but that's you know we're inserting into a sorted set of numbers so saying at the end is a bit nebulous and we are going to say that we want to generate the number of elements requested and then we say what do we put here we need a generator of some sort so for our generator we are going to pass in a Lambda we're going to let It capture by reference anything that's local that we need and we simply want to return the call of the uniform it distribution object taking our generator object as a parameter and we're missing our close here and I just remembered and I forgot to zoom in the font for this let's go with this size okay so now we are generating num elements random numbers and we are inserting them all into our set and then we will return our RV Val now in our main let's simply call make sorted random of let's say a million different values and what we want to know just for the sake of this example is how many unique numbers were generated and returned so we need to include the rest of our headers and IO stream we're compiling with GCC 5 2.1 I believe yes all right and we forgot our algorithm header all right so this takes a couple of seconds for it to generate 1 million random numbers and we see that we're getting approximately 632,000 unique random numbers so we're not fully populating the entire set with the mill million possibilities and we're using 100% of the CPU for approximately 3 seconds now let's enable some optimizations see what differences we get now it's taking 1.57 seconds and we're getting 99% so to get us to the multi-threading capabilities of C++ 11 let's say we wanted to compare two different calls to this and we wanted to see what's the difference in the kind of distribution number of unique numbers generated I don't know it probably make sense to actually compare these two distributions but what we see is that it takes takes approximately twice as long to run two times as many random number generators and we have a two core virtual computer here so let's try to take advantage of both of them and now we're going to talk about Futures so let's say how do we simply create a future something that's going to run in the background and it's kind of shockingly easy we're going to call STD async and we need to include our I believe the header is called thread no header is called future so what we're doing is we're by calling a sync and so we're going to say we want to pass in the function make sorted Rand random we want to pass in the one parameter that it takes 1 million and then we want to call doget size and there's a lot going on in this line of code so I'll break it down in a second let's see where this gets us compiles but we're getting an undefined reference to PID create so we need to link with P thread and now when we run we're still taking 3 seconds and only using 99% of the CPU if we were fully utilizing both cores then we' see something like 199% so why is that so first let's let's break this down this would make more sense what we've got and this line all right this call right here says Auto F1 equals this is telling the computer telling C++ that we want to make the function make sorted random be called asynchronously and we're using STD Asing to do that and what that does is it returns a future and a future is this handy little thing that holds a value that is promised to exist at some point in the future and when we call get on it it returns the value that was stored in the future so we know that the return value of make sorted random is a standard set of inss so that is what here f1. getet would return now kind of the problem with async is that it can choose for us whether or not these things run actually asynchronously or if they run deferred at the moment that get is called so you could use this to ceue up a bunch of different things that you may or may not know if they need to be calculated or not and just put them in deferred and then delay the execution of them for the sake of this specific example we want to force the compiler the runtime to launch these things asynchronously so we can create two of them and then here let's clean this up just a little bit f1.
getet do size and f2. get. size all right we recompile file and now we see that we're using 181% of the system which means nearly two full cores and it's taking 2 seconds instead of 3.4 seconds so we're not getting perfect parallelization but we're getting something and it's really just that easy and the Futures are really cool because they can even do things like store and forward um stor and forward exceptions that have occurred so if we were so inclined we could in here throw an STD runtime error of hello world and now we can say try f1.
getet catch const STD exception reference and say F1 through exception e do what and give that a value compile that and we can actually see here F1 through an exception hello world and we ended up with a um with an uncut exception because we attempted to get the value a second time from f1. down here in our print line so so this is ju really the serious quick start to using standard async and Futures but that's really simple to use and if you really keep it simple by passing in all of the parameters to your asynchronously launched function as copies and return something that is a copy or an internal value and never try to access any global data or any shared data at all you can get really good parallelization results without having to worry about any kind of manual locking so play around with that and as always leave me some comments on my web page if you have any questions or comments and or if there's anything else you'd like me to talk about thanks e
Up Next

Multithreading in C++20: A Beginner's Guide to Concurrency
@CppCon
93.2K views•2022-12-06

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

HTTP Requests Explained: GET, POST, PUT, DELETE
@codecademy
103.1K views•2021-10-07

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science



![[C++ von { bis }] 62 - Paralleles Arbeiten](https://i.ytimg.com/vi/t471l-3gmXM/maxresdefault.jpg)



















![Tajemnica Sandry została odkryta | Praktykanci #9 [4K]](https://i.ytimg.com/vi/E4cdJiMU-MY/maxresdefault.jpg)




















