To see me speak about these topics and go over the code, please watch this youtube video.
In another blog post, we learned about what multithreading is and how to do multithreading in C++. Please refer to that blog post if you're a beginner.
In this blog post, we're going to be looking at advanced C++ multithreading examples.
Starting Out - No Multithreading
So let's say that we have a particular function that we want to use a bunch of times. This function is called srcmakeMulti and can be seen in the following example.
In this particular example, we call the function three times.
We can compile and run this code with the following two lines, in your terminal. We'll be using this command to run all of the following code, as well.
Use Multithreading, But Notice The Issue
That's great, but what if we have to call the function many, many times? We could wait for the functions to execute sequentially, but it would be better to take advantage of multithreading to execute the function as often as we can, to finish quicker.
Fantastic, our code will be much faster now (assuming that our CPU has extra threads available), but we have some issues...
The problem is that we're using shared resources (the 'num' variable and 'cout') between multiple threads, and that leads to errors during execution. If you run the above code a few times, it's obvious that what gets outputted to the console isn't correct, and you get a different answer every time. (If you had one phone and three people, they can't all use the phone at the same time, right?)
Mutexes - Shared Resources Between Multiple Threads
The way we handle this is by "locking" parts of our code while it's using a shared resource. We do this using mutexes. A mutex will not let another thread access the part of the locked code until the mutex finishes executing that piece of code and unlocks it. Notice the four lines of additional code in the following example, and notice that the output is what we expect.
Better For Some Purposes: Async and Futures
If you simply need to spin some work off on separate thread, and do something else while waiting for the return result, then use async and futures. Basically, async does some work on another thread, and the future facilitates the async so that when the task is complete, you can get the return value in the part of your code that you need it.
You can read up on the documentation for futures and async yourself, but for the most part, follow the syntax shown above.
There are a few protips that we should adhere to to ensure that our code is good. These tips are heavily inspired by this article, so read the article after this.
Basically, be careful with your multithreading architecture, if your project is large.
To see me go over the code and speak about the topic, watch the following video:
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels.