std::this_thread::sleep_until

来源:互联网 发布:读出文字的软件 编辑:程序博客网 时间:2024/06/16 00:24

头文件:<thread>                  (C++11)

template<class Clock, class Duration>

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

作用:

阻塞当前正在执行的线程直到sleep_time溢出。

sleep_time是和时钟相关联的,也就是要注意时钟调整会影响到sleep_time。因此,

时钟的时长有可能或没有可能会短于或长于sleep_time。Clock::now()返回调用这个函数时的时间,取决于调整方向。该函数也有可能因为调度或者资源竞争而导致阻塞时间延长到sleep_time溢出之后。

参数:

sleep_time 阻塞时长

返回值:

none

异常:

任何从Clock或Duration抛出的异常(由标准库提供的时钟和时长从来都不会抛出异常)

实例:

#include <iostream>  #include <iomanip>  #include <chrono>  #include <ctime>  #include <thread>  #pragma warning(disable:4996)//加上可去掉unsafe 请使用localtime_s的编译报错  int main()  {      using std::chrono::system_clock;      std::time_t tt = system_clock::to_time_t(system_clock::now());      struct std::tm *ptm = std::localtime(&tt);      std::cout << "Current time: " << std::put_time(ptm, "%X") << '\n'; //必须大写X,若小写x,输出的为日期      std::cout << "Waiting for the next minute to begin...\n";      ++ptm->tm_min;       ptm->tm_sec = 0;      std::this_thread::sleep_until(system_clock::from_time_t(mktime(ptm)));      std::cout << std::put_time(ptm, "%X") << "reached!\n";      getchar();      return 0;  }  

结果:


原创粉丝点击