2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * This module implements a Synchronized abstraction useful in
19 * mutex-based concurrency.
21 * The Synchronized<T, Mutex> class is the primary public API exposed by this
22 * module. See folly/docs/Synchronized.md for a more complete explanation of
23 * this class and its benefits.
28 #include <folly/LockTraits.h>
29 #include <folly/Preprocessor.h>
30 #include <folly/SharedMutex.h>
31 #include <folly/Traits.h>
32 #include <glog/logging.h>
34 #include <type_traits>
38 template <class LockedType, class Mutex, class LockPolicy>
40 template <class LockedType, class LockPolicy>
42 template <class LockedType, class LockPolicy = LockPolicyExclusive>
46 * SynchronizedBase is a helper parent class for Synchronized<T>.
48 * It provides wlock() and rlock() methods for shared mutex types,
49 * or lock() methods for purely exclusive mutex types.
51 template <class Subclass, bool is_shared>
52 class SynchronizedBase;
55 * SynchronizedBase specialization for shared mutex types.
57 * This class provides wlock() and rlock() methods for acquiring the lock and
60 template <class Subclass>
61 class SynchronizedBase<Subclass, true> {
63 using LockedPtr = ::folly::LockedPtr<Subclass, LockPolicyExclusive>;
64 using ConstWLockedPtr =
65 ::folly::LockedPtr<const Subclass, LockPolicyExclusive>;
66 using ConstLockedPtr = ::folly::LockedPtr<const Subclass, LockPolicyShared>;
69 * Acquire an exclusive lock, and return a LockedPtr that can be used to
70 * safely access the datum.
72 * LockedPtr offers operator -> and * to provide access to the datum.
73 * The lock will be released when the LockedPtr is destroyed.
76 return LockedPtr(static_cast<Subclass*>(this));
78 ConstWLockedPtr wlock() const {
79 return ConstWLockedPtr(static_cast<const Subclass*>(this));
83 * Acquire a read lock, and return a ConstLockedPtr that can be used to
84 * safely access the datum.
86 ConstLockedPtr rlock() const {
87 return ConstLockedPtr(static_cast<const Subclass*>(this));
91 * Attempts to acquire the lock, or fails if the timeout elapses first.
92 * If acquisition is unsuccessful, the returned LockedPtr will be null.
94 * (Use LockedPtr::isNull() to check for validity.)
96 template <class Rep, class Period>
97 LockedPtr wlock(const std::chrono::duration<Rep, Period>& timeout) {
98 return LockedPtr(static_cast<Subclass*>(this), timeout);
100 template <class Rep, class Period>
101 ConstWLockedPtr wlock(
102 const std::chrono::duration<Rep, Period>& timeout) const {
103 return ConstWLockedPtr(static_cast<const Subclass*>(this), timeout);
107 * Attempts to acquire the lock, or fails if the timeout elapses first.
108 * If acquisition is unsuccessful, the returned LockedPtr will be null.
110 * (Use LockedPtr::isNull() to check for validity.)
112 template <class Rep, class Period>
113 ConstLockedPtr rlock(
114 const std::chrono::duration<Rep, Period>& timeout) const {
115 return ConstLockedPtr(static_cast<const Subclass*>(this), timeout);
119 * Note: C++ 17 adds guaranteed copy elision. (http://wg21.link/P0135)
120 * Once compilers support this, it would be nice to add wguard() and rguard()
121 * methods that return LockedGuardPtr objects.
125 * Invoke a function while holding the lock exclusively.
127 * A reference to the datum will be passed into the function as its only
130 * This can be used with a lambda argument for easily defining small critical
131 * sections in the code. For example:
133 * auto value = obj.withWLock([](auto& data) {
135 * return data.getValue();
138 template <class Function>
139 auto withWLock(Function&& function) {
140 LockedGuardPtr<Subclass, LockPolicyExclusive> guardPtr(
141 static_cast<Subclass*>(this));
142 return function(*guardPtr);
144 template <class Function>
145 auto withWLock(Function&& function) const {
146 LockedGuardPtr<const Subclass, LockPolicyExclusive> guardPtr(
147 static_cast<const Subclass*>(this));
148 return function(*guardPtr);
152 * Invoke a function while holding the lock exclusively.
154 * This is similar to withWLock(), but the function will be passed a
155 * LockedPtr rather than a reference to the data itself.
157 * This allows scopedUnlock() to be called on the LockedPtr argument if
160 template <class Function>
161 auto withWLockPtr(Function&& function) {
162 return function(wlock());
164 template <class Function>
165 auto withWLockPtr(Function&& function) const {
166 return function(wlock());
170 * Invoke a function while holding an the lock in shared mode.
172 * A const reference to the datum will be passed into the function as its
175 template <class Function>
176 auto withRLock(Function&& function) const {
177 LockedGuardPtr<const Subclass, LockPolicyShared> guardPtr(
178 static_cast<const Subclass*>(this));
179 return function(*guardPtr);
182 template <class Function>
183 auto withRLockPtr(Function&& function) const {
184 return function(rlock());
189 * SynchronizedBase specialization for non-shared mutex types.
191 * This class provides lock() methods for acquiring the lock and accessing the
194 template <class Subclass>
195 class SynchronizedBase<Subclass, false> {
197 using LockedPtr = ::folly::LockedPtr<Subclass, LockPolicyExclusive>;
198 using ConstLockedPtr =
199 ::folly::LockedPtr<const Subclass, LockPolicyExclusive>;
202 * Acquire a lock, and return a LockedPtr that can be used to safely access
206 return LockedPtr(static_cast<Subclass*>(this));
210 * Acquire a lock, and return a ConstLockedPtr that can be used to safely
213 ConstLockedPtr lock() const {
214 return ConstLockedPtr(static_cast<const Subclass*>(this));
218 * Attempts to acquire the lock, or fails if the timeout elapses first.
219 * If acquisition is unsuccessful, the returned LockedPtr will be null.
221 template <class Rep, class Period>
222 LockedPtr lock(const std::chrono::duration<Rep, Period>& timeout) {
223 return LockedPtr(static_cast<Subclass*>(this), timeout);
227 * Attempts to acquire the lock, or fails if the timeout elapses first.
228 * If acquisition is unsuccessful, the returned LockedPtr will be null.
230 template <class Rep, class Period>
231 ConstLockedPtr lock(const std::chrono::duration<Rep, Period>& timeout) const {
232 return ConstLockedPtr(static_cast<const Subclass*>(this), timeout);
236 * Note: C++ 17 adds guaranteed copy elision. (http://wg21.link/P0135)
237 * Once compilers support this, it would be nice to add guard() methods that
238 * return LockedGuardPtr objects.
242 * Invoke a function while holding the lock.
244 * A reference to the datum will be passed into the function as its only
247 * This can be used with a lambda argument for easily defining small critical
248 * sections in the code. For example:
250 * auto value = obj.withLock([](auto& data) {
252 * return data.getValue();
255 template <class Function>
256 auto withLock(Function&& function) {
257 LockedGuardPtr<Subclass, LockPolicyExclusive> guardPtr(
258 static_cast<Subclass*>(this));
259 return function(*guardPtr);
261 template <class Function>
262 auto withLock(Function&& function) const {
263 LockedGuardPtr<const Subclass, LockPolicyExclusive> guardPtr(
264 static_cast<const Subclass*>(this));
265 return function(*guardPtr);
269 * Invoke a function while holding the lock exclusively.
271 * This is similar to withWLock(), but the function will be passed a
272 * LockedPtr rather than a reference to the data itself.
274 * This allows scopedUnlock() and getUniqueLock() to be called on the
275 * LockedPtr argument.
277 template <class Function>
278 auto withLockPtr(Function&& function) {
279 return function(lock());
281 template <class Function>
282 auto withLockPtr(Function&& function) const {
283 return function(lock());
288 * Synchronized<T> encapsulates an object of type T (a "datum") paired
289 * with a mutex. The only way to access the datum is while the mutex
290 * is locked, and Synchronized makes it virtually impossible to do
291 * otherwise. The code that would access the datum in unsafe ways
292 * would look odd and convoluted, thus readily alerting the human
293 * reviewer. In contrast, the code that uses Synchronized<T> correctly
294 * looks simple and intuitive.
296 * The second parameter must be a mutex type. Any mutex type supported by
297 * LockTraits<Mutex> can be used. By default any class with lock() and
298 * unlock() methods will work automatically. LockTraits can be specialized to
299 * teach Synchronized how to use other custom mutex types. See the
300 * documentation in LockTraits.h for additional details.
302 * Supported mutexes that work by default include std::mutex,
303 * std::recursive_mutex, std::timed_mutex, std::recursive_timed_mutex,
304 * folly::SharedMutex, folly::RWSpinLock, and folly::SpinLock.
305 * Include LockTraitsBoost.h to get additional LockTraits specializations to
306 * support the following boost mutex types: boost::mutex,
307 * boost::recursive_mutex, boost::shared_mutex, boost::timed_mutex, and
308 * boost::recursive_timed_mutex.
310 template <class T, class Mutex = SharedMutex>
311 struct Synchronized : public SynchronizedBase<
312 Synchronized<T, Mutex>,
313 LockTraits<Mutex>::is_shared> {
316 SynchronizedBase<Synchronized<T, Mutex>, LockTraits<Mutex>::is_shared>;
317 static constexpr bool nxCopyCtor{
318 std::is_nothrow_copy_constructible<T>::value};
319 static constexpr bool nxMoveCtor{
320 std::is_nothrow_move_constructible<T>::value};
323 using LockedPtr = typename Base::LockedPtr;
324 using ConstLockedPtr = typename Base::ConstLockedPtr;
326 using MutexType = Mutex;
329 * Default constructor leaves both members call their own default
332 Synchronized() = default;
335 * Copy constructor copies the data (with locking the source and
336 * all) but does NOT copy the mutex. Doing so would result in
339 Synchronized(const Synchronized& rhs) noexcept(nxCopyCtor)
340 : Synchronized(rhs, rhs.contextualRLock()) {}
343 * Move constructor moves the data (with locking the source and all)
344 * but does not move the mutex.
346 Synchronized(Synchronized&& rhs) noexcept(nxMoveCtor)
347 : Synchronized(std::move(rhs), rhs.contextualLock()) {}
350 * Constructor taking a datum as argument copies it. There is no
351 * need to lock the constructing object.
353 explicit Synchronized(const T& rhs) noexcept(nxCopyCtor) : datum_(rhs) {}
356 * Constructor taking a datum rvalue as argument moves it. Again,
357 * there is no need to lock the constructing object.
359 explicit Synchronized(T&& rhs) noexcept(nxMoveCtor)
360 : datum_(std::move(rhs)) {}
363 * Lets you construct non-movable types in-place. Use the constexpr
364 * instance `construct_in_place` as the first argument.
366 template <typename... Args>
367 explicit Synchronized(construct_in_place_t, Args&&... args)
368 : datum_(std::forward<Args>(args)...) {}
371 * The canonical assignment operator only assigns the data, NOT the
372 * mutex. It locks the two objects in ascending order of their
375 Synchronized& operator=(const Synchronized& rhs) {
377 // Self-assignment, pass.
378 } else if (this < &rhs) {
379 auto guard1 = operator->();
380 auto guard2 = rhs.operator->();
383 auto guard1 = rhs.operator->();
384 auto guard2 = operator->();
391 * Move assignment operator, only assigns the data, NOT the
392 * mutex. It locks the two objects in ascending order of their
395 Synchronized& operator=(Synchronized&& rhs) {
397 // Self-assignment, pass.
398 } else if (this < &rhs) {
399 auto guard1 = operator->();
400 auto guard2 = rhs.operator->();
401 datum_ = std::move(rhs.datum_);
403 auto guard1 = rhs.operator->();
404 auto guard2 = operator->();
405 datum_ = std::move(rhs.datum_);
411 * Lock object, assign datum.
413 Synchronized& operator=(const T& rhs) {
414 auto guard = operator->();
420 * Lock object, move-assign datum.
422 Synchronized& operator=(T&& rhs) {
423 auto guard = operator->();
424 datum_ = std::move(rhs);
429 * Acquire an appropriate lock based on the context.
431 * If the mutex is a shared mutex, and the Synchronized instance is const,
432 * this acquires a shared lock. Otherwise this acquires an exclusive lock.
434 * In general, prefer using the explicit rlock() and wlock() methods
435 * for read-write locks, and lock() for purely exclusive locks.
437 * contextualLock() is primarily intended for use in other template functions
438 * that do not necessarily know the lock type.
440 LockedPtr contextualLock() {
441 return LockedPtr(this);
443 ConstLockedPtr contextualLock() const {
444 return ConstLockedPtr(this);
446 template <class Rep, class Period>
447 LockedPtr contextualLock(const std::chrono::duration<Rep, Period>& timeout) {
448 return LockedPtr(this, timeout);
450 template <class Rep, class Period>
451 ConstLockedPtr contextualLock(
452 const std::chrono::duration<Rep, Period>& timeout) const {
453 return ConstLockedPtr(this, timeout);
456 * contextualRLock() acquires a read lock if the mutex type is shared,
457 * or a regular exclusive lock for non-shared mutex types.
459 * contextualRLock() when you know that you prefer a read lock (if
460 * available), even if the Synchronized<T> object itself is non-const.
462 ConstLockedPtr contextualRLock() const {
463 return ConstLockedPtr(this);
465 template <class Rep, class Period>
466 ConstLockedPtr contextualRLock(
467 const std::chrono::duration<Rep, Period>& timeout) const {
468 return ConstLockedPtr(this, timeout);
472 * This accessor offers a LockedPtr. In turn, LockedPtr offers
473 * operator-> returning a pointer to T. The operator-> keeps
474 * expanding until it reaches a pointer, so syncobj->foo() will lock
475 * the object and call foo() against it.
477 * NOTE: This API is planned to be deprecated in an upcoming diff.
478 * Prefer using lock(), wlock(), or rlock() instead.
480 LockedPtr operator->() {
481 return LockedPtr(this);
485 * Obtain a ConstLockedPtr.
487 * NOTE: This API is planned to be deprecated in an upcoming diff.
488 * Prefer using lock(), wlock(), or rlock() instead.
490 ConstLockedPtr operator->() const {
491 return ConstLockedPtr(this);
495 * Attempts to acquire for a given number of milliseconds. If
496 * acquisition is unsuccessful, the returned LockedPtr is NULL.
498 * NOTE: This API is deprecated. Use lock(), wlock(), or rlock() instead.
499 * In the future it will be marked with a deprecation attribute to emit
500 * build-time warnings, and then it will be removed entirely.
502 LockedPtr timedAcquire(unsigned int milliseconds) {
503 return LockedPtr(this, std::chrono::milliseconds(milliseconds));
507 * Attempts to acquire for a given number of milliseconds. If
508 * acquisition is unsuccessful, the returned ConstLockedPtr is NULL.
510 * NOTE: This API is deprecated. Use lock(), wlock(), or rlock() instead.
511 * In the future it will be marked with a deprecation attribute to emit
512 * build-time warnings, and then it will be removed entirely.
514 ConstLockedPtr timedAcquire(unsigned int milliseconds) const {
515 return ConstLockedPtr(this, std::chrono::milliseconds(milliseconds));
519 * Sometimes, although you have a mutable object, you only want to
520 * call a const method against it. The most efficient way to achieve
521 * that is by using a read lock. You get to do so by using
522 * obj.asConst()->method() instead of obj->method().
524 * NOTE: This API is planned to be deprecated in an upcoming diff.
525 * Use rlock() instead.
527 const Synchronized& asConst() const {
532 * Swaps with another Synchronized. Protected against
533 * self-swap. Only data is swapped. Locks are acquired in increasing
536 void swap(Synchronized& rhs) {
541 return rhs.swap(*this);
543 auto guard1 = operator->();
544 auto guard2 = rhs.operator->();
547 swap(datum_, rhs.datum_);
551 * Swap with another datum. Recommended because it keeps the mutex
555 LockedPtr guard(this);
562 * Copies datum to a given target.
564 void copy(T* target) const {
565 ConstLockedPtr guard(this);
570 * Returns a fresh copy of the datum.
573 ConstLockedPtr guard(this);
578 template <class LockedType, class MutexType, class LockPolicy>
579 friend class folly::LockedPtrBase;
580 template <class LockedType, class LockPolicy>
581 friend class folly::LockedPtr;
582 template <class LockedType, class LockPolicy>
583 friend class folly::LockedGuardPtr;
586 * Helper constructors to enable Synchronized for
587 * non-default constructible types T.
588 * Guards are created in actual public constructors and are alive
589 * for the time required to construct the object
592 const Synchronized& rhs,
593 const ConstLockedPtr& /*guard*/) noexcept(nxCopyCtor)
594 : datum_(rhs.datum_) {}
596 Synchronized(Synchronized&& rhs, const LockedPtr& /*guard*/) noexcept(
598 : datum_(std::move(rhs.datum_)) {}
600 // Synchronized data members
602 mutable Mutex mutex_;
605 template <class SynchronizedType, class LockPolicy>
606 class ScopedUnlocker;
610 * A helper alias that resolves to "const T" if the template parameter
611 * is a const Synchronized<T>, or "T" if the parameter is not const.
613 template <class SynchronizedType>
614 using SynchronizedDataType = typename std::conditional<
615 std::is_const<SynchronizedType>::value,
616 typename SynchronizedType::DataType const,
617 typename SynchronizedType::DataType>::type;
619 * A helper alias that resolves to a ConstLockedPtr if the template parameter
620 * is a const Synchronized<T>, or a LockedPtr if the parameter is not const.
622 template <class SynchronizedType>
623 using LockedPtrType = typename std::conditional<
624 std::is_const<SynchronizedType>::value,
625 typename SynchronizedType::ConstLockedPtr,
626 typename SynchronizedType::LockedPtr>::type;
630 * A helper base class for implementing LockedPtr.
632 * The main reason for having this as a separate class is so we can specialize
633 * it for std::mutex, so we can expose a std::unique_lock to the caller
634 * when std::mutex is being used. This allows callers to use a
635 * std::condition_variable with the mutex from a Synchronized<T, std::mutex>.
637 * We don't use std::unique_lock with other Mutex types since it makes the
638 * LockedPtr class slightly larger, and it makes the logic to support
639 * ScopedUnlocker slightly more complicated. std::mutex is the only one that
640 * really seems to benefit from the unique_lock. std::condition_variable
641 * itself only supports std::unique_lock<std::mutex>, so there doesn't seem to
642 * be any real benefit to exposing the unique_lock with other mutex types.
644 * Note that the SynchronizedType template parameter may or may not be const
647 template <class SynchronizedType, class Mutex, class LockPolicy>
648 class LockedPtrBase {
650 using MutexType = Mutex;
651 friend class folly::ScopedUnlocker<SynchronizedType, LockPolicy>;
654 * Destructor releases.
658 LockPolicy::unlock(parent_->mutex_);
664 explicit LockedPtrBase(SynchronizedType* parent) : parent_(parent) {
665 LockPolicy::lock(parent_->mutex_);
667 template <class Rep, class Period>
669 SynchronizedType* parent,
670 const std::chrono::duration<Rep, Period>& timeout) {
671 if (LockPolicy::try_lock_for(parent->mutex_, timeout)) {
672 this->parent_ = parent;
675 LockedPtrBase(LockedPtrBase&& rhs) noexcept : parent_(rhs.parent_) {
676 rhs.parent_ = nullptr;
678 LockedPtrBase& operator=(LockedPtrBase&& rhs) noexcept {
680 LockPolicy::unlock(parent_->mutex_);
683 parent_ = rhs.parent_;
684 rhs.parent_ = nullptr;
688 using UnlockerData = SynchronizedType*;
691 * Get a pointer to the Synchronized object from the UnlockerData.
693 * In the generic case UnlockerData is just the Synchronized pointer,
694 * so we return it as is. (This function is more interesting in the
695 * std::mutex specialization below.)
697 static SynchronizedType* getSynchronized(UnlockerData data) {
701 UnlockerData releaseLock() {
702 auto current = parent_;
704 LockPolicy::unlock(current->mutex_);
707 void reacquireLock(UnlockerData&& data) {
708 DCHECK(parent_ == nullptr);
710 LockPolicy::lock(parent_->mutex_);
713 SynchronizedType* parent_ = nullptr;
717 * LockedPtrBase specialization for use with std::mutex.
719 * When std::mutex is used we use a std::unique_lock to hold the mutex.
720 * This makes it possible to use std::condition_variable with a
721 * Synchronized<T, std::mutex>.
723 template <class SynchronizedType, class LockPolicy>
724 class LockedPtrBase<SynchronizedType, std::mutex, LockPolicy> {
726 using MutexType = std::mutex;
727 friend class folly::ScopedUnlocker<SynchronizedType, LockPolicy>;
730 * Destructor releases.
733 // The std::unique_lock will automatically release the lock when it is
734 // destroyed, so we don't need to do anything extra here.
737 LockedPtrBase(LockedPtrBase&& rhs) noexcept
738 : lock_(std::move(rhs.lock_)), parent_(rhs.parent_) {
739 rhs.parent_ = nullptr;
741 LockedPtrBase& operator=(LockedPtrBase&& rhs) noexcept {
742 lock_ = std::move(rhs.lock_);
743 parent_ = rhs.parent_;
744 rhs.parent_ = nullptr;
749 * Get a reference to the std::unique_lock.
751 * This is provided so that callers can use Synchronized<T, std::mutex>
752 * with a std::condition_variable.
754 * While this API could be used to bypass the normal Synchronized APIs and
755 * manually interact with the underlying unique_lock, this is strongly
758 std::unique_lock<std::mutex>& getUniqueLock() {
764 explicit LockedPtrBase(SynchronizedType* parent)
765 : lock_(parent->mutex_), parent_(parent) {}
768 std::pair<std::unique_lock<std::mutex>, SynchronizedType*>;
770 static SynchronizedType* getSynchronized(const UnlockerData& data) {
774 UnlockerData releaseLock() {
775 UnlockerData data(std::move(lock_), parent_);
780 void reacquireLock(UnlockerData&& data) {
781 lock_ = std::move(data.first);
783 parent_ = data.second;
786 // The specialization for std::mutex does have to store slightly more
787 // state than the default implementation.
788 std::unique_lock<std::mutex> lock_;
789 SynchronizedType* parent_ = nullptr;
793 * This class temporarily unlocks a LockedPtr in a scoped manner.
795 template <class SynchronizedType, class LockPolicy>
796 class ScopedUnlocker {
798 explicit ScopedUnlocker(LockedPtr<SynchronizedType, LockPolicy>* p)
799 : ptr_(p), data_(ptr_->releaseLock()) {}
800 ScopedUnlocker(const ScopedUnlocker&) = delete;
801 ScopedUnlocker& operator=(const ScopedUnlocker&) = delete;
802 ScopedUnlocker(ScopedUnlocker&& other) noexcept
803 : ptr_(other.ptr_), data_(std::move(other.data_)) {
804 other.ptr_ = nullptr;
806 ScopedUnlocker& operator=(ScopedUnlocker&& other) = delete;
810 ptr_->reacquireLock(std::move(data_));
815 * Return a pointer to the Synchronized object used by this ScopedUnlocker.
817 SynchronizedType* getSynchronized() const {
818 return LockedPtr<SynchronizedType, LockPolicy>::getSynchronized(data_);
822 using Data = typename LockedPtr<SynchronizedType, LockPolicy>::UnlockerData;
823 LockedPtr<SynchronizedType, LockPolicy>* ptr_{nullptr};
828 * A LockedPtr keeps a Synchronized<T> object locked for the duration of
829 * LockedPtr's existence.
831 * It provides access the datum's members directly by using operator->() and
834 * The LockPolicy parameter controls whether or not the lock is acquired in
835 * exclusive or shared mode.
837 template <class SynchronizedType, class LockPolicy>
838 class LockedPtr : public LockedPtrBase<
840 typename SynchronizedType::MutexType,
843 using Base = LockedPtrBase<
845 typename SynchronizedType::MutexType,
847 using UnlockerData = typename Base::UnlockerData;
848 // CDataType is the DataType with the appropriate const-qualification
849 using CDataType = detail::SynchronizedDataType<SynchronizedType>;
852 using DataType = typename SynchronizedType::DataType;
853 using MutexType = typename SynchronizedType::MutexType;
854 using Synchronized = typename std::remove_const<SynchronizedType>::type;
855 friend class ScopedUnlocker<SynchronizedType, LockPolicy>;
858 * Creates an uninitialized LockedPtr.
860 * Dereferencing an uninitialized LockedPtr is not allowed.
865 * Takes a Synchronized<T> and locks it.
867 explicit LockedPtr(SynchronizedType* parent) : Base(parent) {}
870 * Takes a Synchronized<T> and attempts to lock it, within the specified
873 * Blocks until the lock is acquired or until the specified timeout expires.
874 * If the timeout expired without acquiring the lock, the LockedPtr will be
875 * null, and LockedPtr::isNull() will return true.
877 template <class Rep, class Period>
879 SynchronizedType* parent,
880 const std::chrono::duration<Rep, Period>& timeout)
881 : Base(parent, timeout) {}
886 LockedPtr(LockedPtr&& rhs) noexcept = default;
889 * Move assignment operator.
891 LockedPtr& operator=(LockedPtr&& rhs) noexcept = default;
894 * Copy constructor and assignment operator are deleted.
896 LockedPtr(const LockedPtr& rhs) = delete;
897 LockedPtr& operator=(const LockedPtr& rhs) = delete;
900 * Destructor releases.
905 * Check if this LockedPtr is uninitialized, or points to valid locked data.
907 * This method can be used to check if a timed-acquire operation succeeded.
908 * If an acquire operation times out it will result in a null LockedPtr.
910 * A LockedPtr is always either null, or holds a lock to valid data.
911 * Methods such as scopedUnlock() reset the LockedPtr to null for the
912 * duration of the unlock.
914 bool isNull() const {
915 return this->parent_ == nullptr;
919 * Explicit boolean conversion.
923 explicit operator bool() const {
924 return this->parent_ != nullptr;
928 * Access the locked data.
930 * This method should only be used if the LockedPtr is valid.
932 CDataType* operator->() const {
933 return &this->parent_->datum_;
937 * Access the locked data.
939 * This method should only be used if the LockedPtr is valid.
941 CDataType& operator*() const {
942 return this->parent_->datum_;
946 * Temporarily unlock the LockedPtr, and reset it to null.
948 * Returns an helper object that will re-lock and restore the LockedPtr when
949 * the helper is destroyed. The LockedPtr may not be dereferenced for as
950 * long as this helper object exists.
952 ScopedUnlocker<SynchronizedType, LockPolicy> scopedUnlock() {
953 return ScopedUnlocker<SynchronizedType, LockPolicy>(this);
958 * LockedGuardPtr is a simplified version of LockedPtr.
960 * It is non-movable, and supports fewer features than LockedPtr. However, it
961 * is ever-so-slightly more performant than LockedPtr. (The destructor can
962 * unconditionally release the lock, without requiring a conditional branch.)
964 * The relationship between LockedGuardPtr and LockedPtr is similar to that
965 * between std::lock_guard and std::unique_lock.
967 template <class SynchronizedType, class LockPolicy>
968 class LockedGuardPtr {
970 // CDataType is the DataType with the appropriate const-qualification
971 using CDataType = detail::SynchronizedDataType<SynchronizedType>;
974 using DataType = typename SynchronizedType::DataType;
975 using MutexType = typename SynchronizedType::MutexType;
976 using Synchronized = typename std::remove_const<SynchronizedType>::type;
978 LockedGuardPtr() = delete;
981 * Takes a Synchronized<T> and locks it.
983 explicit LockedGuardPtr(SynchronizedType* parent) : parent_(parent) {
984 LockPolicy::lock(parent_->mutex_);
988 * Destructor releases.
991 LockPolicy::unlock(parent_->mutex_);
995 * Access the locked data.
997 CDataType* operator->() const {
998 return &parent_->datum_;
1002 * Access the locked data.
1004 CDataType& operator*() const {
1005 return parent_->datum_;
1009 // This is the entire state of LockedGuardPtr.
1010 SynchronizedType* const parent_{nullptr};
1014 * Acquire locks for multiple Synchronized<T> objects, in a deadlock-safe
1017 * The locks are acquired in order from lowest address to highest address.
1018 * (Note that this is not necessarily the same algorithm used by std::lock().)
1020 * For parameters that are const and support shared locks, a read lock is
1021 * acquired. Otherwise an exclusive lock is acquired.
1023 * TODO: Extend acquireLocked() with variadic template versions that
1024 * allow for more than 2 Synchronized arguments. (I haven't given too much
1025 * thought about how to implement this. It seems like it would be rather
1026 * complicated, but I think it should be possible.)
1028 template <class Sync1, class Sync2>
1029 std::tuple<detail::LockedPtrType<Sync1>, detail::LockedPtrType<Sync2>>
1030 acquireLocked(Sync1& l1, Sync2& l2) {
1031 if (static_cast<const void*>(&l1) < static_cast<const void*>(&l2)) {
1032 auto p1 = l1.contextualLock();
1033 auto p2 = l2.contextualLock();
1034 return std::make_tuple(std::move(p1), std::move(p2));
1036 auto p2 = l2.contextualLock();
1037 auto p1 = l1.contextualLock();
1038 return std::make_tuple(std::move(p1), std::move(p2));
1043 * A version of acquireLocked() that returns a std::pair rather than a
1044 * std::tuple, which is easier to use in many places.
1046 template <class Sync1, class Sync2>
1047 std::pair<detail::LockedPtrType<Sync1>, detail::LockedPtrType<Sync2>>
1048 acquireLockedPair(Sync1& l1, Sync2& l2) {
1049 auto lockedPtrs = acquireLocked(l1, l2);
1050 return {std::move(std::get<0>(lockedPtrs)),
1051 std::move(std::get<1>(lockedPtrs))};
1054 /************************************************************************
1055 * NOTE: All APIs below this line will be deprecated in upcoming diffs.
1056 ************************************************************************/
1058 // Non-member swap primitive
1059 template <class T, class M>
1060 void swap(Synchronized<T, M>& lhs, Synchronized<T, M>& rhs) {
1065 * SYNCHRONIZED is the main facility that makes Synchronized<T>
1066 * helpful. It is a pseudo-statement that introduces a scope where the
1067 * object is locked. Inside that scope you get to access the unadorned
1072 * Synchronized<vector<int>> svector;
1074 * SYNCHRONIZED (svector) { ... use svector as a vector<int> ... }
1076 * SYNCHRONIZED (v, svector) { ... use v as a vector<int> ... }
1078 * Refer to folly/docs/Synchronized.md for a detailed explanation and more
1081 #define SYNCHRONIZED(...) \
1082 FOLLY_PUSH_WARNING \
1083 FOLLY_GCC_DISABLE_WARNING(shadow) \
1084 if (bool SYNCHRONIZED_state = false) { \
1086 for (auto SYNCHRONIZED_lockedPtr = \
1087 (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).operator->(); \
1088 !SYNCHRONIZED_state; \
1089 SYNCHRONIZED_state = true) \
1090 for (auto& FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)) = \
1091 *SYNCHRONIZED_lockedPtr.operator->(); \
1092 !SYNCHRONIZED_state; \
1093 SYNCHRONIZED_state = true) \
1096 #define TIMED_SYNCHRONIZED(timeout, ...) \
1097 if (bool SYNCHRONIZED_state = false) { \
1099 for (auto SYNCHRONIZED_lockedPtr = \
1100 (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).timedAcquire(timeout); \
1101 !SYNCHRONIZED_state; \
1102 SYNCHRONIZED_state = true) \
1103 for (auto FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)) = \
1104 (!SYNCHRONIZED_lockedPtr \
1106 : SYNCHRONIZED_lockedPtr.operator->()); \
1107 !SYNCHRONIZED_state; \
1108 SYNCHRONIZED_state = true)
1111 * Similar to SYNCHRONIZED, but only uses a read lock.
1113 #define SYNCHRONIZED_CONST(...) \
1115 FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)), \
1116 (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).asConst())
1119 * Similar to TIMED_SYNCHRONIZED, but only uses a read lock.
1121 #define TIMED_SYNCHRONIZED_CONST(timeout, ...) \
1122 TIMED_SYNCHRONIZED( \
1124 FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)), \
1125 (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).asConst())
1128 * Temporarily disables synchronization inside a SYNCHRONIZED block.
1130 * Note: This macro is deprecated, and kind of broken. The input parameter
1131 * does not control what it unlocks--it always unlocks the lock acquired by the
1132 * most recent SYNCHRONIZED scope. If you have two nested SYNCHRONIZED blocks,
1133 * UNSYNCHRONIZED always unlocks the inner-most, even if you pass in the
1134 * variable name used in the outer SYNCHRONIZED block.
1136 * This macro will be removed soon in a subsequent diff.
1138 #define UNSYNCHRONIZED(name) \
1139 for (auto SYNCHRONIZED_state3 = SYNCHRONIZED_lockedPtr.scopedUnlock(); \
1140 !SYNCHRONIZED_state; \
1141 SYNCHRONIZED_state = true) \
1142 for (auto& name = *SYNCHRONIZED_state3.getSynchronized(); \
1143 !SYNCHRONIZED_state; \
1144 SYNCHRONIZED_state = true)
1147 * Synchronizes two Synchronized objects (they may encapsulate
1148 * different data). Synchronization is done in increasing address of
1149 * object order, so there is no deadlock risk.
1151 #define SYNCHRONIZED_DUAL(n1, e1, n2, e2) \
1152 if (bool SYNCHRONIZED_state = false) { \
1154 for (auto SYNCHRONIZED_ptrs = acquireLockedPair(e1, e2); \
1155 !SYNCHRONIZED_state; \
1156 SYNCHRONIZED_state = true) \
1157 for (auto& n1 = *SYNCHRONIZED_ptrs.first; !SYNCHRONIZED_state; \
1158 SYNCHRONIZED_state = true) \
1159 for (auto& n2 = *SYNCHRONIZED_ptrs.second; !SYNCHRONIZED_state; \
1160 SYNCHRONIZED_state = true)
1162 } /* namespace folly */