函式
<thread>

std::this_thread::sleep_for

template <class Rep, class Period>  void sleep_for (const chrono::duration<Rep,Period>& rel_time);
按時間跨度休眠
阻塞呼叫執行緒的執行,持續時間由 rel_time 指定。

當前執行緒的執行會暫停,直到至少 rel_time 時間過去。其他執行緒將繼續執行。

引數

rel_time
呼叫執行緒恢復執行之前要經過的時間跨度。
請注意,多執行緒管理操作可能會導致超過此時間的延遲。
duration 是一個表示特定相對時間的物件。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// this_thread::sleep_for example
#include <iostream>       // std::cout, std::endl
#include <thread>         // std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds
 
int main() 
{
  std::cout << "countdown:\n";
  for (int i=10; i>0; --i) {
    std::cout << i << std::endl;
    std::this_thread::sleep_for (std::chrono::seconds(1));
  }
  std::cout << "Lift off!\n";

  return 0;
}

輸出(10秒後)
countdown:
10
9
8
7
6
5
4
3
2
1
Lift off!


異常安全

如果 rel_time 的型別從不丟擲異常(例如,標頭檔案 <chrono> 中的 duration 例項化),則此函式也從不丟擲異常(無異常保證)。

另見