Imported Upstream version 1.72.0
[platform/upstream/boost.git] / libs / outcome / doc / src / content / reference / aliases / lazy.md
1 +++
2 title = "`lazy<T>/atomic_lazy<T>`"
3 description = "A lazily evaluated coroutine awaitable with Outcome customisation."
4 +++
5
6 This is very similar to {{% api "eager<T>" %}}, except that execution of the
7 `lazy<T>` returning function suspends immediately. Functions which return `lazy<T>`
8 are therefore suitable for tasks which you need to instantiate right now, but whose
9 execution will occur elsewhere e.g. in a separate kernel thread. Because of the very
10 common use case of using worker threads to execute the body of lazily executed
11 coroutines, most people will want to use `atomic_lazy<T>` instead of `lazy<T>`.
12
13 `atomic_lazy<T>` is like `lazy<T>`, except that the setting of the coroutine result
14 performs an atomic release, whilst the checking of whether the coroutine has finished
15 is an atomic acquire.
16
17 `lazy<T>` has similar semantics to `std::lazy<T>`, which is being standardised. See
18 https://wg21.link/P1056 *Add lazy coroutine (coroutine task) type*.
19
20 Example of use (must be called from within a coroutinised function):
21
22 ```c++
23 lazy<int> func(int x)
24 {
25   co_return x + 1;
26 }
27 ...
28 // Always suspends perhaps causing other coroutines to execute, then resumes.
29 int r = co_await func(5);
30 ```
31
32 `lazy<T>` has special semantics if `T` is a type capable of constructing from
33 an `exception_ptr` or `error_code` -- any exceptions thrown during the function's body
34 are sent via `T`, preferably via the error code route if {{% api "error_from_exception(" %}}`)`
35 successfully matches the exception throw. This means that a {{% api "basic_result<T, E, NoValuePolicy>" %}}
36 or {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}} where one of its types is
37 is compatible will have its `.error()` or `.exception()` set.
38
39 Note that `lazy<T>` does not otherwise transport exception throws, and rethrows
40 any exceptions thrown within the coroutine body through the coroutine machinery.
41 This does not produce reliable consequences in current C++ compilers. You should
42 therefore wrap the coroutine body in a `try...catch` if `T` is not able to transport
43 exceptions on its own.
44
45 *Requires*: C++ coroutines to be available in your compiler.
46
47 *Namespace*: `BOOST_OUTCOME_V2_NAMESPACE::awaitables`
48
49 *Header*: `<boost/outcome/coroutine_support.hpp>`