Debian Codegraph @

thirdparty/folly/folly/concurrency/ThreadCachedSynchronized.h

raw symbols SCIP
1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <cstdint>
20 #include <memory>
21 #include <type_traits>
22 #include <utility>
23
24 #include <folly/SharedMutex.h>
25 #include <folly/ThreadLocal.h>
26 #include <folly/Utility.h>
27 #include <folly/lang/Access.h>
28 #include <folly/synchronization/Lock.h>
29 #include <folly/synchronization/RelaxedAtomic.h>
30
31 namespace folly {
32
33 // thread_cached_synchronized
34 //
35 // Roughly equivalent to Synchronized, but with a per-thread cache for
36 // acceleration.
37 //
38 // Use in hot code when Synchronized alone, with its shared lock and unlock,
39 // would be too costly.
40 //
41 // Avoid when acceleration is marginal since per-thread caches are expensive.
42 //
43 // Example:
44 //
45 // struct writer_and_readers {
46 // folly::thread_cached_synchronized<std::shared_ptr<data>> obj_;
47 // std::jthread background_writer_{std::bind(loop_update, this)};
48 //
49 // std::shared_ptr<data> get_recent_data_fast() { return obj; }
50 //
51 // data fetch_recent_data();
52 // bool needs_data_and_not_signaled_done();
53 // void loop_update() {
54 // while (needs_data_and_not_signaled_done()) {
55 // obj.exchange(folly::copy_to_shared_ptr(fetch_recent_data()));
56 // }
57 // }
58 // };
59 //
60 // Note:
61 // A singleton variation of this with SingletonThreadLocal would remove one
62 // of the branches when looking up the per-thread cache but would introduce
63 // a new branch when looking up the global version.
64 template <typename T, typename Mutex = SharedMutex>
65 class thread_cached_synchronized {
66 static_assert(std::is_same<std::decay_t<T>, T>::value, "not decayed");
67 static_assert(std::is_copy_constructible<T>::value, "not copy-constructible");
68
69 public:
70 using value_type = T;
71
72 private:
73 using version_type = std::uint64_t; // 64 bits will not overflow
74
75 struct truth_state {
76 relaxed_atomic<version_type> version{0}; // tiny optimization if first field
77 Mutex mutex{}; // protects value and sometimes version
78 value_type value;
79
80 template <typename... A>
81 truth_state(A&&... a) noexcept(
82 std::is_nothrow_constructible<Mutex>{} &&
83 std::is_nothrow_constructible<value_type, A...>{})
84 : value{static_cast<A&&>(a)...} {}
85 };
86
87 struct cache_state {
88 version_type version{0};
89 value_type value;
90
91 template <typename... A>
92 cache_state(A&&... a) //
93 noexcept(std::is_nothrow_constructible<value_type, A...>{})
94 : value{static_cast<A&&>(a)...} {}
95 };
96 using tlp_cache_state = ThreadLocalPtr<cache_state>;
97
98 template <typename... A>
99 static constexpr bool nx = noexcept(truth_state{
100 in_place, FOLLY_DECLVAL(A)...});
101
102 template <bool C>
103 using if_ = std::enable_if_t<C, int>;
104
105 using swap_fn = access::swap_fn;
106
107 public:
108 template <typename A = value_type, if_<std::is_constructible<A>{}> = 0>
109 thread_cached_synchronized() noexcept(nx<>) : truth_{in_place} {}
110 explicit thread_cached_synchronized(value_type const& a) //
111 noexcept(nx<value_type const&>)
112 : truth_{a} {}
113 explicit thread_cached_synchronized(value_type&& a) noexcept(nx<value_type&&>)
114 : truth_{static_cast<value_type&&>(a)} {}
115 template <typename A, if_<std::is_constructible<value_type, A>{}> = 0>
116 explicit thread_cached_synchronized(A&& a) noexcept(nx<A&&>)
117 : truth_{static_cast<A&&>(a)} {}
118 template <typename... A, if_<std::is_constructible<value_type, A...>{}> = 0>
119 explicit thread_cached_synchronized(in_place_t, A&&... a) noexcept(nx<A&&...>)
120 : truth_{static_cast<A&&>(a)...} {}
121
122 template <typename A, if_<std::is_assignable<value_type&, A>{}> = 0>
123 thread_cached_synchronized& operator=(A&& a) noexcept(false) {
124 store(static_cast<A&&>(a));
125 return *this;
126 }
127
128 template <typename A = value_type>
129 void store(A&& a = A{}) {
130 mutate([&](auto& value) { value = static_cast<A&&>(a); });
131 }
132
133 template <typename A = value_type>
134 value_type exchange(A&& a = A{}) {
135 return mutate([&](auto& value) { //
136 return std::exchange(value, static_cast<A&&>(a));
137 });
138 }
139
140 template <typename A>
141 bool compare_exchange(value_type& expected, A&& desired) {
142 return mutate_cx(expected, static_cast<A&&>(desired));
143 }
144
145 template <typename A>
146 void swap(A& that) noexcept(false) {
147 mutate([&](auto& value) { access::swap(value, that); });
148 }
149
150 template <typename A, if_<is_invocable_v<swap_fn, value_type&, A&>> = 0>
151 friend void swap(thread_cached_synchronized& self, A& that) noexcept(false) {
152 self.swap(that);
153 }
154
155 value_type const& operator*() const { return ref(); }
156 value_type const* operator->() const { return std::addressof(ref()); }
157 value_type load() const { return folly::as_const(ref()); }
158 /* implicit */ operator value_type() const { return load(); }
159
160 private:
161 void invalidate_caches() {
162 truth_.version = truth_.version + 1; // intentionally not +=
163 }
164
165 // TODO: past C++17, just use if-constexpr in mutate()
166 template <
167 typename F,
168 typename R = invoke_result_t<F, value_type&>,
169 if_<std::is_void<R>{}> = 0>
170 R mutate_locked(F f) {
171 f(truth_.value); // value first: mutation may throw
172 invalidate_caches();
173 }
174 template <
175 typename F,
176 typename R = invoke_result_t<F, value_type&>,
177 if_<!std::is_void<R>{}> = 0>
178 R mutate_locked(F f) {
179 decltype(auto) ret = f(truth_.value); // value first: mutation may throw
180 invalidate_caches();
181 return ret;
182 }
183 template <typename F, typename R = invoke_result_t<F, value_type&>>
184 R mutate(F f) {
185 unique_lock<Mutex> lock{truth_.mutex};
186 return mutate_locked(f);
187 }
188
189 template <typename A>
190 bool mutate_cx(value_type& expected, A&& desired) {
191 unique_lock<Mutex> lock{truth_.mutex};
192 auto const eq = folly::as_const(truth_.value) == folly::as_const(expected);
193 if (eq) {
194 truth_.value = // value first: mutation may throw
195 static_cast<A&&>(desired);
196 invalidate_caches();
197 } else {
198 expected = folly::as_const(truth_.value);
199 }
200 return eq;
201 }
202
203 FOLLY_ERASE value_type& ref() const {
204 auto const cache = cache_.get();
205 auto const unexpired = cache && cache->version == truth_.version;
206 return FOLLY_LIKELY(unexpired) ? cache->value : get_slow();
207 }
208
209 FOLLY_NOINLINE value_type& get_slow() const {
210 hybrid_lock<Mutex> lock{truth_.mutex};
211 auto cache = cache_.get();
212 if (cache == nullptr) {
213 cache = new cache_state{truth_.value}; // value first: copy may throw
214 cache_.reset(cache);
215 } else {
216 cache->value = truth_.value; // value first: copy may throw
217 }
218 cache->version = truth_.version;
219 return cache->value;
220 }
221
222 mutable truth_state truth_;
223 mutable tlp_cache_state cache_;
224 };
225
226 } // namespace folly