A nice and simple possibility to control threads came with C++11. It introduced the this_thread
namespace, which includes functions that affect only the caller thread. It contains two different functions that allow putting a thread to sleep for a certain amount of time, so we do not need to use any external or operating system-dependent libraries for such tasks any longer.
In this recipe, we concentrate on how to suspend threads for a certain amount of time, or how to put them to sleep.
We will write a short program that just puts the main thread to sleep for certain amounts of time:
- Let's first include all the needed headers and declare that we'll use the
std
andchrono_literals
namespaces. Thechrono_literals
namespace contains handy abbreviations for creating time-span values:
#include <iostream> #include <chrono> #include <thread> using namespace std; using namespace...