public member function
<future>

std::promise::set_value

generic template (1)
void set_value (const T& val);void set_value (T&& val);
specializations (2)
void promise<R&>::set_value (R& val);   // when T is a reference type (R&)void promise<void>::set_value (void);   // when T is void
Set value
val 儲存為 *shared state* 中的值,使其變為 *ready*。

如果與同一個 *shared state* 關聯的 future 物件當前正在等待 future::get 的呼叫,則會解除阻塞並返回 val

void 特化版本中的成員僅使 *shared state* 變為 ready,而不設定任何值。

引數

val
*shared state* 的值。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// promise example
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int (std::future<int>& fut) {
  int x = fut.get();
  std::cout << "value: " << x << '\n';
}

int main ()
{
  std::promise<int> prom;                      // create promise

  std::future<int> fut = prom.get_future();    // engagement with future

  std::thread th1 (print_int, std::ref(fut));  // send future to new thread

  prom.set_value (10);                         // fulfill promise
                                               // (synchronizes with getting the future)
  th1.join();
  return 0;
}

輸出

value: 10


資料競爭

promise 物件被修改。
共享狀態被修改為原子操作(不會導致資料競爭)。

異常安全

基本保證:如果丟擲異常,則 promise 物件處於有效狀態。

此成員函式在以下條件下丟擲異常
exception typeerror condition描述
future_errorfuture_errc::no_state該物件沒有共享狀態(它已被移動賦值
future_errorfuture_errc::promise_already_satisfied共享狀態已儲存值或異常
如果用於複製/移動 val 的建構函式丟擲異常(對於 *(1)*),此成員函式也會丟擲異常,並且(取決於庫實現)也可能丟擲以報告其他情況。

另見