From 2a7c46fa2a18a023bf05a8ed95830bd85a4b46da Mon Sep 17 00:00:00 2001 From: I <1091761+wx257osn2@users.noreply.github.com> Date: Sat, 4 Jan 2025 09:11:44 +0900 Subject: [PATCH] add example to see difference between `wait_for(0s) == ready` and `valid()` --- reference/future/future/wait_for.md | 51 ++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/reference/future/future/wait_for.md b/reference/future/future/wait_for.md index fd77159de..2f079ffd8 100644 --- a/reference/future/future/wait_for.md +++ b/reference/future/future/wait_for.md @@ -30,6 +30,7 @@ future_status wait_for(const chrono::duration& rel_time) const; ## 例 +### 例1 ```cpp example #include #include @@ -70,11 +71,59 @@ int main() * std::future_status[link /reference/future/future_status.md] * f.get()[link /reference/future/shared_future/get.md] -### 出力例 +#### 出力例 ``` 3 ``` +### 例2 +```cpp example +#include +#include +#include + +int main() +{ + std::promise p; + std::future f = p.get_future(); + const auto ready = [&f] { + return f.wait_for(std::chrono::seconds{0}) == std::future_status::ready; + }; + + // まだ値はセットされていない + std::cout << std::boolalpha << ready() << std::endl; + + p.set_value(1); + + // 値がセットされた + std::cout << std::boolalpha << ready() << std::endl; + + f.get(); // 一度値を取り出すと共有状態が破棄される + + // 共有状態を持たない(valid() == falseな)futureでwaitをするとstd::future_error例外 + try { + ready(); + } + catch(const std::future_error& e) { + std::cout << e.what() << std::endl; + } +} +``` +* wait_for[color ff0000] +* std::promise[link /reference/future/promise.md] +* p.set_value[link /reference/future/promise/set_value.md] +* std::future_status[link /reference/future/future_status.md] +* f.get()[link /reference/future/shared_future/get.md] +* valid()[link /reference/future/future/valid.md] +* std::future_error[link /reference/future/future_error.md] + +#### 出力例 +``` +false +true +std::future_error: No associated state +``` + ## バージョン ### 言語 - C++11