Namespaces
Variants

std::this_thread:: sleep_for

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
sleep_for
(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 Rep, class Period >
void sleep_for ( const std:: chrono :: duration < Rep, Period > & sleep_duration ) ;
(C++11以降)

現在のスレッドの実行を指定された 少なくとも sleep_duration の間ブロックします。

この関数は、スケジューリングやリソース競合による遅延のため、 sleep_duration よりも長くブロックする可能性があります。

標準では、時間の計測には安定したクロックを使用することが推奨されています。実装がシステムクロックを使用する場合、待機時間はクロック調整の影響を受ける可能性もあります。

目次

パラメータ

sleep_duration - スリープする時間間隔

戻り値

(なし)

例外

clock time_point 、または duration によって実行中に送出される例外(標準ライブラリで提供されるクロック、タイムポイント、およびデュレーションは例外を送出しません)。

#include <chrono>
#include <iostream>
#include <thread>
int main()
{
    using namespace std::chrono_literals;
    std::cout << "Hello waiter\n" << std::flush;
    const auto start = std::chrono::high_resolution_clock::now();
    std::this_thread::sleep_for(2000ms);
    const auto end = std::chrono::high_resolution_clock::now();
    const std::chrono::duration<double, std::milli> elapsed = end - start;
    std::cout << "Waited " << elapsed << '\n';
}

出力例:

Hello waiter
Waited 2000.13 ms

関連項目

指定された時間ポイントまで現在のスレッドの実行を停止する
(関数)