C ++ 11 threads sleep_until

Header: <Thread> ( C ++ . 11)

template<class Clock, class Duration>

void sleep_until(const std::chrono::time_point<Clock, Duration>& sleep_time);

effect:

Currently executing thread is blocked until sleep_time overflow.

sleep_time and the clock is associated, that is, to pay attention to the clock adjustment will affect the sleep_time. therefore,

Duration may or may not have a clock may be shorter or longer than sleep_time. Clock :: now () Returns the time when this function is called, depending on the direction of adjustment. This function is also possible because of scheduling or resource competition caused by prolonged obstruction after sleep_time to overflow.

parameter:

Long blocked sleep_time

return value:

none

abnormal:

Clock or from any exceptions thrown Duration (clock and duration provided by the standard library never throw an exception)

Example:

Copy the code

 1 #include <iostream>  
 2 #include <iomanip>  
 3 #include <chrono>  
 4 #include <ctime>  
 5 #include <thread>  
 6 #pragma warning (disable: 4996) // plus can remove unsafe use localtime_s compiler error  
 7 int main ()  
 8 {  
 9     using std::chrono::system_clock;  
10     std::time_t tt = system_clock::to_time_t(system_clock::now());  
11     struct std::tm *ptm = std::localtime(&tt);  
12 std :: cout << "Current time:" << std :: put_time (ptm, "% X") << '\ n'; // must be capitalized X, if the lowercase x, output date  
13     std::cout << "Waiting for the next minute to begin...\n";  
14     ++ptm->tm_min;   
15     ptm->tm_sec = 0;  
16     std::this_thread::sleep_until(system_clock::from_time_t(mktime(ptm)));  
17     std::cout << std::put_time(ptm, "%X") << "reached!\n";  
18     getchar();  
19     return 0;  
20 }  

Copy the code

result:

Published 257 original articles · won praise 22 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_24127015/article/details/104812320