Sleep for a Specific Amount of Time

Learn to use the sleep function to put a thread to sleep for a specific amount of time.

We'll cover the following

The <thread> header provides two functions for putting a thread to sleep, sleep_for() and sleep_until(). Both functions are in the std::this_thread namespace.

How to do it

Let's look at how to use the sleep_for() and sleep_until() functions:

  • The sleep-related functions are in the std::this_thread namespace. Because it has just a few symbols, we'll go ahead and issue using directives for std::this_thread and std::chrono_literals:

Get hands-on with 1200+ tech skills courses.