sleep_for — this_thread::sleep_for

sleep_for — this_thread::sleep_for

std::this_thread::sleep_for현재 스레드의 실행을 지정된 sleep_duration '이상' 막는 함수예요. C++11에서 도입됐어요. <thread> 헤더에 있어요.

스케줄링·리소스 경합 때문에 sleep_duration보다 더 오래 막힐 수 있어요.

출처: cppreference

본문

// <thread> 헤더, C++11
template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );

사용 예

#include <thread>
#include <chrono>
#include <iostream>

using namespace std::chrono_literals;

std::this_thread::sleep_for(std::chrono::milliseconds(100));  // 100ms
std::this_thread::sleep_for(2s);        // 2초 (리터럴)
std::this_thread::sleep_for(500ms);     // 500ms

특징

  • 지정한 시간 "이상" 잠들어요. OS 스케줄링 지연으로 정확히 그 시간은 아니게 될 수 있어요.
  • sleep_for(0)스레드 양보(yield)에 가까운 동작을 해요 (플랫폼 의존).
  • 정밀한 대기 시각이 필요하면 sleep_until을 써요.
// 폴링 루프에서 짧게 대기
while (!ready_flag.load()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
}

주의

  • 단위는 std::chrono::duration이어요 — chrono_literalsms, s 등을 쓸 수 있어요.
  • 음의 duration은 즉시 반환돼요.

sleep_for는 테스트, 폴링, 타이밍 제어 등에서 현재 스레드를 일정 시간 멈추는 표준 방법이에요.

더 알아보기 (Learn more)

cppreference