Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Disposer.hpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2021 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#ifndef TOOLBOX_IO_DISPOSER_HPP
18#define TOOLBOX_IO_DISPOSER_HPP
19
20#include <toolbox/sys/Time.hpp>
22
23namespace toolbox {
24inline namespace io {
25
28template <typename DerivedT>
30 public:
32
33 // Copy.
36
37 // Move.
40
43 {
44 if (locks_ == 0) {
45 // Prevent the object from being disposed a second time by holding a lock
46 // indefinitely.
47 locks_ = 1;
48 static_cast<DerivedT*>(this)->dispose_now(now);
49 } else {
50 dispose_ = true;
51 }
52 }
53
54 protected:
55 ~BasicDisposer() = default;
56
58 bool is_locked() const noexcept { return locks_ > 0; }
59
62 [[nodiscard]] auto lock_this(CyclTime now) noexcept
63 {
64 ++locks_;
65 return make_finally([this, now]() noexcept {
66 if (--locks_ == 0 && dispose_) {
67 // Prevent the object from being disposed a second time by holding a lock
68 // indefinitely.
69 locks_ = 1;
70 static_cast<DerivedT*>(this)->dispose_now(now);
71 }
72 });
73 }
74
75 private:
76 short locks_{0};
77 bool dispose_{false};
78};
79
80} // namespace io
81} // namespace toolbox
82
83#endif // TOOLBOX_IO_DISPOSER_HPP
auto lock_this(CyclTime now) noexcept
Definition Disposer.hpp:62
BasicDisposer() noexcept=default
bool is_locked() const noexcept
Returns true if the lock is held or the object has been disposed.
Definition Disposer.hpp:58
void dispose(CyclTime now) noexcept
The dispose method may be safely called from callback functions while a lock is held.
Definition Disposer.hpp:42
auto make_finally(FnT fn) noexcept
Definition Finally.hpp:48
constexpr auto bind() noexcept
Definition Slot.hpp:92