In this article we will discuss how to put a c++11 thread to sleep.

c++11 provides 2 functions for putting a thread to sleep i.e.

Sleep for a Duration

C++11 provides a function std::this_thread::sleep_for to block the current thread for specified duration i.e.

This function accepts a duration as an argument and make the calling thread to sleep for that particular duration.

This duration can be from nanoseconds to hours i.e.

Lets see some examples,

Sleeping a Thread for MilliSeconds:

To sleep a thread for 200 Milliseconds call sleep_for with following argument i.e.

Sleeping a Thread for Minutes:

To sleep a thread for 1 Minute call sleep_for with following argument i.e.

Checkout complete example as follows,

Output:

Sleep Until a TimePoint

Many times we want the thread to sleep untill a time point in future. That can be acieved using sleep_untill() i.e.

It accepts a time point as an argument and blocks the current thread till this time point is achieved.

Checkout the complete example, here we will put a thread to sleep until a time point in future i.e.

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.