公有成員函式
<future>

std::future::wait_for

template <class Rep, class Period>  future_status wait_for (const chrono::duration<Rep,Period>& rel_time) const;
等待就緒,持續一段時間
等待指定時間段 rel_time 以內,使*共享狀態*就緒。

如果*共享狀態*尚未就緒(即,提供者尚未設定其值或異常),則該函式將阻塞呼叫執行緒,直到其*就緒*或直到 rel_time 時間已過,以先發生的為準。

當函式因其*共享狀態*就緒而返回時,*共享狀態*上設定的值或異常不會被讀取,但所有可見的副作用將在提供者使*共享狀態*就緒的那一點與此函式返回之間同步。

如果*共享狀態*包含一個*延遲函式*(例如由 async 返回的 future 物件),則該函式不會阻塞,而是立即返回,返回值為 future_status::deferred

引數

rel_time
等待時間段,此後函式將返回並恢復呼叫執行緒的執行。
請注意,多執行緒管理操作可能會導致超過此時間的延遲。
duration 是一個代表特定*相對時間*的物件。

返回值

一個 future_status 型別的值,指示導致函式返回的原因
描述
future_status::ready共享狀態 已就緒:生產者已設定值或異常。
future_status::timeout函式等待 rel_time 時間,而*共享狀態*未就緒。
future_status::deferred共享狀態 包含 延遲函式

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// future::wait_for
#include <iostream>       // std::cout
#include <future>         // std::async, std::future
#include <chrono>         // std::chrono::milliseconds

// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
  for (int i=2; i<x; ++i) if (x%i==0) return false;
  return true;
}

int main ()
{
  // call function asynchronously:
  std::future<bool> fut = std::async (is_prime,700020007); 

  // do something while waiting for function to set future:
  std::cout << "checking, please wait";
  std::chrono::milliseconds span (100);
  while (fut.wait_for(span)==std::future_status::timeout)
    std::cout << '.';

  bool x = fut.get();

  std::cout << "\n700020007 " << (x?"is":"is not") << " prime.\n";

  return 0;
}

可能的輸出(可能需要更多或更少的時間)

checking, please wait..........................................
700020007 is prime.


資料競爭

訪問了 future 物件。
共享狀態 作為 原子操作 被訪問(不會導致資料競爭)。

異常安全

在*未有效*的 future 物件上呼叫此成員函式,會產生*未定義行為*(儘管庫實現可能會檢測到這一點並丟擲帶有 no_state *錯誤條件*的 future_error,提供強擔保)。

如果與 rel_time 相關的操作丟擲異常,則此函式可能丟擲異常(請注意,在 <chrono> 中提供的*時長*型別(如 seconds)上的操作永遠不會丟擲異常)。

另見