sleep_until — this_thread::sleep_until

sleep_until — this_thread::sleep_until

std::this_thread::sleep_until현재 스레드의 실행을 지정된 sleep_time에 도달할 때까지 막는 함수예요. C++11에서 도입됐어요. <thread> 헤더에 있어요.

특정 시각까지 잠드는 것이므로, sleep_for(일정 시간)와 달리 "절대 시각" 기준이에요.

출처: cppreference

본문

// <thread> 헤더, C++11
template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock, Duration>& sleep_time );

사용 예

#include <thread>
#include <chrono>

// 1초 후의 시각까지 잠듦
auto until = std::chrono::steady_clock::now() + std::chrono::seconds(1);
std::this_thread::sleep_until(until);

sleep_untilsteady_clock::now() + duration 형태와 짝을 이뤄 "이 시각까지" 잠드는 지연에 적합해요. 주기적인 스케줄링(고정 간격 루프)에서 드리프트 없이 유지할 때 유용해요.

사용 예 — 고정 주기 루프

auto next = std::chrono::steady_clock::now();
const auto period = std::chrono::milliseconds(100);

for (int i = 0; i < 10; ++i) {
    // 작업 수행
    next += period;                       // 다음 시각 누적
    std::this_thread::sleep_until(next);  // 그 시각까지 대기 (드리프트 누적 방지)
}

특징

  • 절대 시각 기준 — sleep_for처럼 매번 duration을 더하는 방식보다 주기 지터가 적어요.
  • 원하는 시각이 이미 지났으면 즉시 반환돼요.
  • std::chrono::time_point를 인자로 받아요.
// 특정 시각까지 대기
std::this_thread::sleep_until(
    std::chrono::system_clock::now() + std::chrono::seconds(5));

sleep_until은 "특정 시각에 맞춰" 스레드를 깨우는 주기·타이밍 제어에 적합해요.

더 알아보기 (Learn more)

cppreference