Skip to content

Commit

Permalink
add example to see difference between wait_for(0s) == ready and `va…
Browse files Browse the repository at this point in the history
…lid()`
  • Loading branch information
wx257osn2 committed Jan 4, 2025
1 parent 3bd8c4f commit 2a7c46f
Showing 1 changed file with 50 additions and 1 deletion.
51 changes: 50 additions & 1 deletion reference/future/future/wait_for.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const;
## 例
### 例1
```cpp example
#include <iostream>
#include <future>
Expand Down Expand Up @@ -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 <iostream>
#include <future>
#include <chrono>

int main()
{
std::promise<int> p;
std::future<int> 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
Expand Down

0 comments on commit 2a7c46f

Please sign in to comment.