Another addition that came with C++11 is the std::thread
class. It provides a clean and simple way to start and stop threads, without any need for external libraries or to know how the operating system implements this. It's all just included in the STL.
In this recipe, we will implement a program that starts and stops threads. There are some minor details to know what to do with threads once they are started, so we will go through these too.
We will start multiple threads and see how our program behaves when we unleash multiple processor cores to execute parts of its code at the same time:
- At first, we need to include only two headers and then we declare that we use the
std
andchrono_literals
namespaces:
#include <iostream> #include <thread> using namespace std; using namespace chrono_literals;
- In order to start a thread, we need to be able to tell what code should be executed by it. So, let's define a function...