std::this_thread::sleep_for

定义于头文件 <thread>
template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );
(C++11 起)

阻塞当前线程执行,以至少为指定的 sleep_duration

此函数可能阻塞长于 sleep_duration ,因为调度或资源争议延迟。

标准库建议用稳定时钟度量时长。若实现用系统时间代替,则等待时间亦可能对始终调节敏感。

目录

参数

sleep_duration - 要睡眠的时长

返回值

(无)

异常

任何时钟、 time_point 或 duration 在执行间抛出的异常(标准库提供的时钟、时间点和时长决不抛出)。

示例

#include <iostream>
#include <chrono>
#include <thread>
 
int main()
{
    using namespace std::chrono_literals;
    std::cout << "Hello waiter" << std::endl; // 有意冲入
    auto start = std::chrono::high_resolution_clock::now();
    std::this_thread::sleep_for(2s);
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed = end-start;
    std::cout << "Waited " << elapsed.count() << " ms\n";
}

可能的输出:

Hello waiter
Waited 2000.12 ms

参阅

(C++11)
暂停当前线程的执行直到特定的时间点
(函数)

版本历史

  • (当前 | 先前 2017年12月13日 (三) 07:24Fruderica讨论 | 贡献 . . (1,442字节) (-109). . (undo) (撤销)
  • 当前 | 先前 2017年12月12日 (二) 20:08Fruderica讨论 | 贡献 . . (1,551字节) (+125). . (for C++11) (撤销)
  • 当前 | 先前 2017年8月25日 (五) 00:55Fruderica讨论 | 贡献. . (1,426字节) (-179). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:35P12bot讨论 | 贡献 . . (1,605字节) (-51). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 18:37P12bot讨论 | 贡献 . . (1,656字节) (+225). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,431字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,431字节) (+1,431). . (Translated from the English version using Google Translate)