Namespaces
Variants

std::this_thread:: sleep_until

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
(C++11)
sleep_until
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <thread>
template < class Clock, class Duration >
void sleep_until ( const std:: chrono :: time_point < Clock, Duration > & sleep_time ) ;
(C++11 起)

阻塞当前线程的执行,直至达到指定的 sleep_time

Clock 必须满足 Clock 要求。 如果 std:: chrono :: is_clock_v < Clock > false ,则程序非良构。 (since C++20)

标准建议使用与 sleep_time 绑定的时钟,这种情况下可能会考虑对时钟的调整。因此,阻塞的持续时间可能长于或短于调用时 sleep_time - Clock :: now ( ) 的值,具体取决于调整的方向以及实现是否遵循该调整。该函数也可能因进程调度或资源竞争延迟而阻塞直到超过 sleep_time 指定的时间点。

目录

参数

sleep_time - 阻塞直到的时间

返回值

(无)

异常

任何由 Clock Duration 抛出的异常(标准库提供的时钟和持续时间从不抛出异常)。

示例

#include <chrono>
#include <iostream>
#include <thread>
auto now() { return std::chrono::steady_clock::now(); }
auto awake_time()
{
    using std::chrono::operator""ms;
    return now() + 2000ms;
}
int main()
{
    std::cout << "Hello, waiter...\n" << std::flush;
    const auto start{now()};
    std::this_thread::sleep_until(awake_time());
    std::chrono::duration<double, std::milli> elapsed{now() - start};
    std::cout << "Waited " << elapsed.count() << " ms\n";
}

可能的输出:

Hello, waiter...
Waited 2000.17 ms

参见

(C++11)
暂停当前线程执行指定的时间长度
(函数)
C 文档 for thrd_sleep