Debian Codegraph @

js/src/threading/ExclusiveData.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef threading_ExclusiveData_h
8 #define threading_ExclusiveData_h
9
10 #include "mozilla/Maybe.h"
11 #include "mozilla/OperatorNewExtensions.h"
12
13 #include <utility>
14
15 #include "threading/ConditionVariable.h"
16 #include "threading/Mutex.h"
17
18 namespace js {
19
20 /**
21 * [SMDOC] ExclusiveData API
22 *
23 * A mutual exclusion lock class.
24 *
25 * `ExclusiveData` provides an RAII guard to automatically lock and unlock when
26 * accessing the protected inner value.
27 *
28 * Unlike the STL's `std::mutex`, the protected value is internal to this
29 * class. This is a huge win: one no longer has to rely on documentation to
30 * explain the relationship between a lock and its protected data, and the type
31 * system can enforce[0] it.
32 *
33 * For example, suppose we have a counter class:
34 *
35 * class Counter
36 * {
37 * int32_t i;
38 *
39 * public:
40 * void inc(int32_t n) { i += n; }
41 * };
42 *
43 * If we share a counter across threads with `std::mutex`, we rely solely on
44 * comments to document the relationship between the lock and its data, like
45 * this:
46 *
47 * class SharedCounter
48 * {
49 * // Remember to acquire `counter_lock` when accessing `counter`,
50 * // pretty please!
51 * Counter counter;
52 * std::mutex counter_lock;
53 *
54 * public:
55 * void inc(size_t n) {
56 * // Whoops, forgot to acquire the lock! Off to the races!
57 * counter.inc(n);
58 * }
59 * };
60 *
61 * In contrast, `ExclusiveData` wraps the protected value, enabling the type
62 * system to enforce that we acquire the lock before accessing the value:
63 *
64 * class SharedCounter
65 * {
66 * ExclusiveData<Counter> counter;
67 *
68 * public:
69 * void inc(size_t n) {
70 * auto guard = counter.lock();
71 * guard->inc(n);
72 * }
73 * };
74 *
75 * The API design is based on Rust's `std::sync::Mutex<T>` type.
76 *
77 * [0]: Of course, we don't have a borrow checker in C++, so the type system
78 * cannot guarantee that you don't stash references received from
79 * `ExclusiveData<T>::Guard` somewhere such that the reference outlives the
80 * guard's lifetime and therefore becomes invalid. To help avoid this last
81 * foot-gun, prefer using the guard directly! Do not store raw references
82 * to the protected value in other structures!
83 */
84 template <typename T>
85 class ExclusiveData {
86 protected:
87 mutable Mutex lock_ MOZ_UNANNOTATED;
88 mutable T value_;
89
90 ExclusiveData(const ExclusiveData&) = delete;
91 ExclusiveData& operator=(const ExclusiveData&) = delete;
92
93 void acquire() const { lock_.lock(); }
94 void release() const { lock_.unlock(); }
95
96 public:
97 /**
98 * Create a new `ExclusiveData`, with perfect forwarding of the protected
99 * value.
100 */
101 template <typename U>
102 explicit ExclusiveData(const MutexId& id, U&& u)
103 : lock_(id), value_(std::forward<U>(u)) {}
104
105 /**
106 * Create a new `ExclusiveData`, constructing the protected value in place.
107 */
108 template <typename... Args>
109 explicit ExclusiveData(const MutexId& id, Args&&... args)
110 : lock_(id), value_(std::forward<Args>(args)...) {}
111
112 ExclusiveData& operator=(ExclusiveData&& rhs) {
113 this->~ExclusiveData();
114 new (mozilla::KnownNotNull, this) ExclusiveData(std::move(rhs));
115 return *this;
116 }
117
118 /**
119 * An RAII class that provides exclusive access to a `ExclusiveData<T>`'s
120 * protected inner `T` value.
121 *
122 * Note that this is intentionally marked MOZ_STACK_CLASS instead of
123 * MOZ_RAII_CLASS, as the latter disallows moves and returning by value, but
124 * Guard utilizes both.
125 */
126 class MOZ_STACK_CLASS Guard {
127 protected:
128 const ExclusiveData* parent_;
129 explicit Guard(std::nullptr_t) : parent_(nullptr) {}
130
131 private:
132 Guard(const Guard&) = delete;
133 Guard& operator=(const Guard&) = delete;
134
135 public:
136 explicit Guard(const ExclusiveData& parent) : parent_(&parent) {
137 parent_->acquire();
138 }
139
140 Guard(Guard&& rhs) : parent_(rhs.parent_) {
141 MOZ_ASSERT(&rhs != this, "self-move disallowed!");
142 rhs.parent_ = nullptr;
143 }
144
145 Guard& operator=(Guard&& rhs) {
146 this->~Guard();
147 new (this) Guard(std::move(rhs));
148 return *this;
149 }
150
151 T& get() const {
152 MOZ_ASSERT(parent_);
153 return parent_->value_;
154 }
155
156 operator T&() const { return get(); }
157 T* operator->() const { return &get(); }
158
159 const ExclusiveData<T>* parent() const {
160 MOZ_ASSERT(parent_);
161 return parent_;
162 }
163
164 ~Guard() {
165 if (parent_) {
166 parent_->release();
167 }
168 }
169 };
170
171 /**
172 * NullableGuard are similar to Guard, except that one the access to the
173 * ExclusiveData might not always be granted. This is useful when contextual
174 * information is enough to prevent useless use of Mutex.
175 *
176 * The NullableGuard can be manipulated as follows:
177 *
178 * if (NullableGuard guard = data.mightAccess()) {
179 * // NullableGuard is acquired.
180 * guard->...
181 * }
182 * // NullableGuard was either not acquired or released.
183 *
184 * Where mightAccess returns either a NullableGuard from `noAccess()` or a
185 * Guard from `lock()`.
186 */
187 class MOZ_STACK_CLASS NullableGuard : public Guard {
188 public:
189 explicit NullableGuard(std::nullptr_t) : Guard((std::nullptr_t) nullptr) {}
190 explicit NullableGuard(const ExclusiveData& parent) : Guard(parent) {}
191 explicit NullableGuard(Guard&& rhs) : Guard(std::move(rhs)) {}
192
193 NullableGuard& operator=(Guard&& rhs) {
194 this->~NullableGuard();
195 new (this) NullableGuard(std::move(rhs));
196 return *this;
197 }
198
199 /**
200 * Returns whether this NullableGuard has access to the exclusive data.
201 */
202 bool hasAccess() const { return this->parent_; }
203 explicit operator bool() const { return hasAccess(); }
204 };
205
206 /**
207 * Access the protected inner `T` value for exclusive reading and writing.
208 */
209 Guard lock() const { return Guard(*this); }
210
211 /**
212 * Provide a no-access guard, which coerces to false when tested. This value
213 * can be returned if the guard access is conditioned on external factors.
214 *
215 * See NullableGuard.
216 */
217 NullableGuard noAccess() const {
218 return NullableGuard((std::nullptr_t) nullptr);
219 }
220 };
221
222 template <class T>
223 class ExclusiveWaitableData : public ExclusiveData<T> {
224 using Base = ExclusiveData<T>;
225
226 mutable ConditionVariable condVar_;
227
228 public:
229 template <typename U>
230 explicit ExclusiveWaitableData(const MutexId& id, U&& u)
231 : Base(id, std::forward<U>(u)) {}
232
233 template <typename... Args>
234 explicit ExclusiveWaitableData(const MutexId& id, Args&&... args)
235 : Base(id, std::forward<Args>(args)...) {}
236
237 class MOZ_STACK_CLASS Guard : public ExclusiveData<T>::Guard {
238 using Base = typename ExclusiveData<T>::Guard;
239
240 public:
241 explicit Guard(const ExclusiveWaitableData& parent) : Base(parent) {}
242
243 Guard(Guard&& guard) : Base(std::move(guard)) {}
244
245 Guard& operator=(Guard&& rhs) { return Base::operator=(std::move(rhs)); }
246
247 void wait() {
248 auto* parent = static_cast<const ExclusiveWaitableData*>(this->parent());
249 parent->condVar_.wait(parent->lock_);
250 }
251
252 void notify_one() {
253 auto* parent = static_cast<const ExclusiveWaitableData*>(this->parent());
254 parent->condVar_.notify_one();
255 }
256
257 void notify_all() {
258 auto* parent = static_cast<const ExclusiveWaitableData*>(this->parent());
259 parent->condVar_.notify_all();
260 }
261 };
262
263 Guard lock() const { return Guard(*this); }
264 };
265
266 /**
267 * Multiple-readers / single-writer variant of ExclusiveData.
268 *
269 * Readers call readLock() to obtain a stack-only RAII reader lock, which will
270 * allow other readers to read concurrently but block writers; the yielded value
271 * is const. Writers call writeLock() to obtain a ditto writer lock, which
272 * yields exclusive access to non-const data.
273 *
274 * See ExclusiveData and its implementation for more documentation.
275 */
276 template <typename T>
277 class RWExclusiveData {
278 mutable Mutex lock_ MOZ_UNANNOTATED;
279 mutable ConditionVariable cond_;
280 mutable T value_;
281 mutable int readers_;
282
283 // We maintain a count of active readers. Writers may enter the critical
284 // section only when the reader count is zero, so the reader that decrements
285 // the count to zero must wake up any waiting writers.
286 //
287 // There can be multiple writers waiting, so a writer leaving the critical
288 // section must also wake up any other waiting writers.
289
290 void acquireReaderLock() const {
291 lock_.lock();
292 readers_++;
293 lock_.unlock();
294 }
295
296 void releaseReaderLock() const {
297 lock_.lock();
298 MOZ_ASSERT(readers_ > 0);
299 if (--readers_ == 0) {
300 cond_.notify_all();
301 }
302 lock_.unlock();
303 }
304
305 void acquireWriterLock() const {
306 lock_.lock();
307 while (readers_ > 0) {
308 cond_.wait(lock_);
309 }
310 }
311
312 void releaseWriterLock() const {
313 cond_.notify_all();
314 lock_.unlock();
315 }
316
317 public:
318 RWExclusiveData(const RWExclusiveData&) = delete;
319 RWExclusiveData& operator=(const RWExclusiveData&) = delete;
320
321 /**
322 * Create a new `RWExclusiveData`, constructing the protected value in place.
323 */
324 template <typename... Args>
325 explicit RWExclusiveData(const MutexId& id, Args&&... args)
326 : lock_(id), value_(std::forward<Args>(args)...), readers_(0) {}
327
328 class MOZ_STACK_CLASS ReadGuard {
329 const RWExclusiveData* parent_;
330 explicit ReadGuard(std::nullptr_t) : parent_(nullptr) {}
331
332 public:
333 ReadGuard(const ReadGuard&) = delete;
334 ReadGuard& operator=(const ReadGuard&) = delete;
335
336 explicit ReadGuard(const RWExclusiveData& parent) : parent_(&parent) {
337 parent_->acquireReaderLock();
338 }
339
340 ReadGuard(ReadGuard&& rhs) : parent_(rhs.parent_) {
341 MOZ_ASSERT(&rhs != this, "self-move disallowed!");
342 rhs.parent_ = nullptr;
343 }
344
345 ReadGuard& operator=(ReadGuard&& rhs) {
346 this->~ReadGuard();
347 new (this) ReadGuard(std::move(rhs));
348 return *this;
349 }
350
351 const T& get() const {
352 MOZ_ASSERT(parent_);
353 return parent_->value_;
354 }
355
356 operator const T&() const { return get(); }
357 const T* operator->() const { return &get(); }
358
359 const RWExclusiveData<T>* parent() const {
360 MOZ_ASSERT(parent_);
361 return parent_;
362 }
363
364 ~ReadGuard() {
365 if (parent_) {
366 parent_->releaseReaderLock();
367 }
368 }
369 };
370
371 class MOZ_STACK_CLASS WriteGuard {
372 const RWExclusiveData* parent_;
373 explicit WriteGuard(std::nullptr_t) : parent_(nullptr) {}
374
375 public:
376 WriteGuard(const WriteGuard&) = delete;
377 WriteGuard& operator=(const WriteGuard&) = delete;
378
379 explicit WriteGuard(const RWExclusiveData& parent) : parent_(&parent) {
380 parent_->acquireWriterLock();
381 }
382
383 WriteGuard(WriteGuard&& rhs) : parent_(rhs.parent_) {
384 MOZ_ASSERT(&rhs != this, "self-move disallowed!");
385 rhs.parent_ = nullptr;
386 }
387
388 WriteGuard& operator=(WriteGuard&& rhs) {
389 this->~WriteGuard();
390 new (this) WriteGuard(std::move(rhs));
391 return *this;
392 }
393
394 T& get() const {
395 MOZ_ASSERT(parent_);
396 return parent_->value_;
397 }
398
399 operator T&() const { return get(); }
400 T* operator->() const { return &get(); }
401
402 const RWExclusiveData<T>* parent() const {
403 MOZ_ASSERT(parent_);
404 return parent_;
405 }
406
407 ~WriteGuard() {
408 if (parent_) {
409 parent_->releaseWriterLock();
410 }
411 }
412 };
413
414 ReadGuard readLock() const { return ReadGuard(*this); }
415 WriteGuard writeLock() const { return WriteGuard(*this); }
416 };
417
418 } // namespace js
419
420 #endif // threading_ExclusiveData_h