userver: userver/utils/impl/wait_token_storage.hpp Source File
Loading...
Searching...
No Matches
wait_token_storage.hpp
1#pragma once
2
3#include <atomic>
4#include <cstdint>
5
6#include <userver/engine/single_use_event.hpp>
7
8USERVER_NAMESPACE_BEGIN
9
10namespace utils::impl {
11
12// Gives out tokens and waits for all given-out tokens death
13class WaitTokenStorage final {
14 public:
15 class Token final {
16 public:
17 Token() noexcept = default;
18 Token(Token&&) noexcept;
19 Token(const Token&) noexcept;
20 Token& operator=(Token&&) noexcept;
21 Token& operator=(const Token&) noexcept;
22 ~Token();
23
24 /// For internal use only
25 explicit Token(WaitTokenStorage& storage) noexcept;
26
27 private:
28 WaitTokenStorage* storage_{nullptr};
29 };
30
31 WaitTokenStorage();
32
33 WaitTokenStorage(const WaitTokenStorage&) = delete;
34 WaitTokenStorage(WaitTokenStorage&&) = delete;
35 ~WaitTokenStorage();
36
37 Token GetToken();
38
39 /// Approximate number of currently alive tokens
40 std::uint64_t AliveTokensApprox() const noexcept;
41
42 /// Wait until all given-out tokens are dead. Should be called at most once,
43 /// either in a coroutine environment or after the coroutine environment
44 /// stops (during static destruction).
45 void WaitForAllTokens() noexcept;
46
47 private:
48 std::atomic<std::int64_t> tokens_;
49 engine::SingleUseEvent event_;
50};
51
52} // namespace utils::impl
53
54USERVER_NAMESPACE_END