← Patterns

Sleep

123456789101112#include <chrono> #include <thread> using namespace std::literals::chrono_literals; int main() { std::chrono::milliseconds sleepDuration(20); std::this_thread::sleep_for(sleepDuration); std::this_thread::sleep_for(5s); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Block the execution of a thread for a given amount of time.

Description

On line 7, we create a std::chrono::milliseconds object representing the number of milliseconds to sleep (other duration units may also be used). On line 8, the call to std::this_thread::sleep_for will block the execution of the current thread for at least the given duration.

On line 10, we demonstrate the use of C++14’s duration literal suffixes by representing a duration with the seconds suffix, s. The using directive on line 4 is required in order to use these suffixes.

Contributors

  • Joseph Mansfield
  • Paul Walmsley

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share