In this tutorial we’ll discuss one of the more advanced programming concepts, C++ Multithreading and Concurrency.
Proper Multithreading support in C++ was introduced in the C++ 11 version. So if you are still using an older version, then be sure to update. Before C++ 11, we had to use the <pthread> library, which used POSIX.
With C++ 11 however, we now have a powerful yet simple library called <thread>. std::thread is the Class representing threads, out of which we create objects to create additional threads. By passing in the proper parameters, you have these threads execute commands and functions.
Understanding C++ Multithreading
Multithreading is often treated as a complex and difficult topic, and for good reason. Like any important topic however, proper usage and proper understanding will make things infinitely easier.
Uptil now, you’ve been executing all your code on a single thread. However, this is often far too slow, hence we have introduced the concept of multi-threading. To summarize, it’s basically the concept of using Multiple threads, each running independently of each other, but all running in parallel to complete a task(s).
While creating and launching simple threads is an easy task, managing 3 – 4 threads working in parallel, without interfering with each other, yet working alongside each other is a much harder task.
What is Thread?
By now we’ve mentioned the word “thread ” several times. A thread is like a “virtual” core. For the purpose of this article, you need to maintain this line of thinking. Think of each thread as a separate processing unit that can execute a program. And adding more threads into your program gives you more processing units to work with.
Here’s a little diagram we came up with to help you understand threads and multithreading. It’s a very simplified version, but it explains the basic principle behind multithreading. Each circle represents a thread and each rectangle represents a task that will take a minute to perform..
