userver: userver/engine/task/shared_task.hpp Source File
Loading...
Searching...
No Matches
shared_task.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/task/shared_task.hpp
4/// @brief @copybrief engine::SharedTask
5
6#include <memory>
7#include <type_traits>
8#include <utility>
9
10#include <userver/engine/impl/task_context_holder.hpp>
11#include <userver/engine/task/task.hpp>
12#include <userver/engine/task/task_processor_fwd.hpp>
13
14USERVER_NAMESPACE_BEGIN
15
16namespace engine {
17
18/// @brief Asynchronous task that has a shared ownership of the payload.
19///
20/// @warning This class has no `Get` and cannot report exceptions thrown by the
21/// task payload. Prefer
22/// @ref engine::SharedTaskWithResult "SharedTaskWithResult<void>" even when no
23/// result is needed.
24///
25/// See @ref engine::SharedTaskWithResult for a type that could return a value or
26/// report an exception from the payload.
27class [[nodiscard]] SharedTask : public TaskBase {
28public:
29 /// @brief Default constructor
30 ///
31 /// Creates an invalid task.
33
34 /// @brief If the task is still valid and is not finished and this is the last
35 /// shared owner of the payload, cancels the task and waits until it finishes.
37
38 /// @brief Assigns the other task into this.
39 SharedTask(const SharedTask& other) noexcept;
40
41 /// @brief If this task is still valid and is not finished and other task is
42 /// not the same task as this and this is the
43 /// last shared owner of the payload, cancels the task and waits until it
44 /// finishes before assigning the other. Otherwise just assigns the other task
45 /// into this.
46 SharedTask& operator=(const SharedTask& other) noexcept;
47
48 /// @brief Moves the other task into this, leaving the other in an invalid
49 /// state.
50 SharedTask(SharedTask&& other) noexcept;
51
52 /// @brief If this task is still valid and is not finished and other task is
53 /// not the same task as this and this is the
54 /// last shared owner of the payload, cancels the task and waits until it
55 /// finishes before move assigning the other. Otherwise just move assigns the
56 /// other task into this, leaving the other in an invalid state.
57 SharedTask& operator=(SharedTask&& other) noexcept;
58
59 /// Satisfies @ref engine::Awaitable, for use with @ref engine::WaitAnyContext and friends.
60 AwaitableToken GetAwaitableToken() noexcept USERVER_IMPL_LIFETIME_BOUND;
61
62 /// @cond
63 static constexpr WaitMode kWaitMode = WaitMode::kMultipleAwaiters;
64
65protected:
66 // For internal use only.
67 explicit SharedTask(impl::TaskContextHolder&& context);
68 /// @endcond
69
70private:
71 void DecrementSharedUsages() noexcept;
72 void IncrementSharedUsages() noexcept;
73};
74
75} // namespace engine
76
77USERVER_NAMESPACE_END