add an unlock() method to Synchronized<T>::LockedPtr
[folly.git] / folly / Synchronized.h
1 /*
2  * Copyright 2016 Facebook, Inc.
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 /**
18  * This module implements a Synchronized abstraction useful in
19  * mutex-based concurrency.
20  *
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.
24  */
25
26 #pragma once
27
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>
33 #include <mutex>
34 #include <type_traits>
35
36 namespace folly {
37
38 template <class LockedType, class Mutex, class LockPolicy>
39 class LockedPtrBase;
40 template <class LockedType, class LockPolicy>
41 class LockedPtr;
42 template <class LockedType, class LockPolicy = LockPolicyExclusive>
43 class LockedGuardPtr;
44
45 /**
46  * SynchronizedBase is a helper parent class for Synchronized<T>.
47  *
48  * It provides wlock() and rlock() methods for shared mutex types,
49  * or lock() methods for purely exclusive mutex types.
50  */
51 template <class Subclass, bool is_shared>
52 class SynchronizedBase;
53
54 /**
55  * SynchronizedBase specialization for shared mutex types.
56  *
57  * This class provides wlock() and rlock() methods for acquiring the lock and
58  * accessing the data.
59  */
60 template <class Subclass>
61 class SynchronizedBase<Subclass, true> {
62  public:
63   using LockedPtr = ::folly::LockedPtr<Subclass, LockPolicyExclusive>;
64   using ConstWLockedPtr =
65       ::folly::LockedPtr<const Subclass, LockPolicyExclusive>;
66   using ConstLockedPtr = ::folly::LockedPtr<const Subclass, LockPolicyShared>;
67
68   /**
69    * Acquire an exclusive lock, and return a LockedPtr that can be used to
70    * safely access the datum.
71    *
72    * LockedPtr offers operator -> and * to provide access to the datum.
73    * The lock will be released when the LockedPtr is destroyed.
74    */
75   LockedPtr wlock() {
76     return LockedPtr(static_cast<Subclass*>(this));
77   }
78   ConstWLockedPtr wlock() const {
79     return ConstWLockedPtr(static_cast<const Subclass*>(this));
80   }
81
82   /**
83    * Acquire a read lock, and return a ConstLockedPtr that can be used to
84    * safely access the datum.
85    */
86   ConstLockedPtr rlock() const {
87     return ConstLockedPtr(static_cast<const Subclass*>(this));
88   }
89
90   /**
91    * Attempts to acquire the lock, or fails if the timeout elapses first.
92    * If acquisition is unsuccessful, the returned LockedPtr will be null.
93    *
94    * (Use LockedPtr::isNull() to check for validity.)
95    */
96   template <class Rep, class Period>
97   LockedPtr wlock(const std::chrono::duration<Rep, Period>& timeout) {
98     return LockedPtr(static_cast<Subclass*>(this), timeout);
99   }
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);
104   }
105
106   /**
107    * Attempts to acquire the lock, or fails if the timeout elapses first.
108    * If acquisition is unsuccessful, the returned LockedPtr will be null.
109    *
110    * (Use LockedPtr::isNull() to check for validity.)
111    */
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);
116   }
117
118   /*
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.
122    */
123
124   /**
125    * Invoke a function while holding the lock exclusively.
126    *
127    * A reference to the datum will be passed into the function as its only
128    * argument.
129    *
130    * This can be used with a lambda argument for easily defining small critical
131    * sections in the code.  For example:
132    *
133    *   auto value = obj.withWLock([](auto& data) {
134    *     data.doStuff();
135    *     return data.getValue();
136    *   });
137    */
138   template <class Function>
139   auto withWLock(Function&& function) {
140     LockedGuardPtr<Subclass, LockPolicyExclusive> guardPtr(
141         static_cast<Subclass*>(this));
142     return function(*guardPtr);
143   }
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);
149   }
150
151   /**
152    * Invoke a function while holding the lock exclusively.
153    *
154    * This is similar to withWLock(), but the function will be passed a
155    * LockedPtr rather than a reference to the data itself.
156    *
157    * This allows scopedUnlock() to be called on the LockedPtr argument if
158    * desired.
159    */
160   template <class Function>
161   auto withWLockPtr(Function&& function) {
162     return function(wlock());
163   }
164   template <class Function>
165   auto withWLockPtr(Function&& function) const {
166     return function(wlock());
167   }
168
169   /**
170    * Invoke a function while holding an the lock in shared mode.
171    *
172    * A const reference to the datum will be passed into the function as its
173    * only argument.
174    */
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);
180   }
181
182   template <class Function>
183   auto withRLockPtr(Function&& function) const {
184     return function(rlock());
185   }
186 };
187
188 /**
189  * SynchronizedBase specialization for non-shared mutex types.
190  *
191  * This class provides lock() methods for acquiring the lock and accessing the
192  * data.
193  */
194 template <class Subclass>
195 class SynchronizedBase<Subclass, false> {
196  public:
197   using LockedPtr = ::folly::LockedPtr<Subclass, LockPolicyExclusive>;
198   using ConstLockedPtr =
199       ::folly::LockedPtr<const Subclass, LockPolicyExclusive>;
200
201   /**
202    * Acquire a lock, and return a LockedPtr that can be used to safely access
203    * the datum.
204    */
205   LockedPtr lock() {
206     return LockedPtr(static_cast<Subclass*>(this));
207   }
208
209   /**
210    * Acquire a lock, and return a ConstLockedPtr that can be used to safely
211    * access the datum.
212    */
213   ConstLockedPtr lock() const {
214     return ConstLockedPtr(static_cast<const Subclass*>(this));
215   }
216
217   /**
218    * Attempts to acquire the lock, or fails if the timeout elapses first.
219    * If acquisition is unsuccessful, the returned LockedPtr will be null.
220    */
221   template <class Rep, class Period>
222   LockedPtr lock(const std::chrono::duration<Rep, Period>& timeout) {
223     return LockedPtr(static_cast<Subclass*>(this), timeout);
224   }
225
226   /**
227    * Attempts to acquire the lock, or fails if the timeout elapses first.
228    * If acquisition is unsuccessful, the returned LockedPtr will be null.
229    */
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);
233   }
234
235   /*
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.
239    */
240
241   /**
242    * Invoke a function while holding the lock.
243    *
244    * A reference to the datum will be passed into the function as its only
245    * argument.
246    *
247    * This can be used with a lambda argument for easily defining small critical
248    * sections in the code.  For example:
249    *
250    *   auto value = obj.withLock([](auto& data) {
251    *     data.doStuff();
252    *     return data.getValue();
253    *   });
254    */
255   template <class Function>
256   auto withLock(Function&& function) {
257     LockedGuardPtr<Subclass, LockPolicyExclusive> guardPtr(
258         static_cast<Subclass*>(this));
259     return function(*guardPtr);
260   }
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);
266   }
267
268   /**
269    * Invoke a function while holding the lock exclusively.
270    *
271    * This is similar to withWLock(), but the function will be passed a
272    * LockedPtr rather than a reference to the data itself.
273    *
274    * This allows scopedUnlock() and getUniqueLock() to be called on the
275    * LockedPtr argument.
276    */
277   template <class Function>
278   auto withLockPtr(Function&& function) {
279     return function(lock());
280   }
281   template <class Function>
282   auto withLockPtr(Function&& function) const {
283     return function(lock());
284   }
285 };
286
287 /**
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.
295  *
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.
301  *
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.
309  */
310 template <class T, class Mutex = SharedMutex>
311 struct Synchronized : public SynchronizedBase<
312                           Synchronized<T, Mutex>,
313                           LockTraits<Mutex>::is_shared> {
314  private:
315   using Base =
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};
321
322  public:
323   using LockedPtr = typename Base::LockedPtr;
324   using ConstLockedPtr = typename Base::ConstLockedPtr;
325   using DataType = T;
326   using MutexType = Mutex;
327
328   /**
329    * Default constructor leaves both members call their own default
330    * constructor.
331    */
332   Synchronized() = default;
333
334   /**
335    * Copy constructor copies the data (with locking the source and
336    * all) but does NOT copy the mutex. Doing so would result in
337    * deadlocks.
338    */
339   Synchronized(const Synchronized& rhs) noexcept(nxCopyCtor)
340       : Synchronized(rhs, rhs.contextualRLock()) {}
341
342   /**
343    * Move constructor moves the data (with locking the source and all)
344    * but does not move the mutex.
345    */
346   Synchronized(Synchronized&& rhs) noexcept(nxMoveCtor)
347       : Synchronized(std::move(rhs), rhs.contextualLock()) {}
348
349   /**
350    * Constructor taking a datum as argument copies it. There is no
351    * need to lock the constructing object.
352    */
353   explicit Synchronized(const T& rhs) noexcept(nxCopyCtor) : datum_(rhs) {}
354
355   /**
356    * Constructor taking a datum rvalue as argument moves it. Again,
357    * there is no need to lock the constructing object.
358    */
359   explicit Synchronized(T&& rhs) noexcept(nxMoveCtor)
360       : datum_(std::move(rhs)) {}
361
362   /**
363    * Lets you construct non-movable types in-place. Use the constexpr
364    * instance `construct_in_place` as the first argument.
365    */
366   template <typename... Args>
367   explicit Synchronized(construct_in_place_t, Args&&... args)
368       : datum_(std::forward<Args>(args)...) {}
369
370   /**
371    * The canonical assignment operator only assigns the data, NOT the
372    * mutex. It locks the two objects in ascending order of their
373    * addresses.
374    */
375   Synchronized& operator=(const Synchronized& rhs) {
376     if (this == &rhs) {
377       // Self-assignment, pass.
378     } else if (this < &rhs) {
379       auto guard1 = operator->();
380       auto guard2 = rhs.operator->();
381       datum_ = rhs.datum_;
382     } else {
383       auto guard1 = rhs.operator->();
384       auto guard2 = operator->();
385       datum_ = rhs.datum_;
386     }
387     return *this;
388   }
389
390   /**
391    * Move assignment operator, only assigns the data, NOT the
392    * mutex. It locks the two objects in ascending order of their
393    * addresses.
394    */
395   Synchronized& operator=(Synchronized&& rhs) {
396     if (this == &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_);
402     } else {
403       auto guard1 = rhs.operator->();
404       auto guard2 = operator->();
405       datum_ = std::move(rhs.datum_);
406     }
407     return *this;
408   }
409
410   /**
411    * Lock object, assign datum.
412    */
413   Synchronized& operator=(const T& rhs) {
414     auto guard = operator->();
415     datum_ = rhs;
416     return *this;
417   }
418
419   /**
420    * Lock object, move-assign datum.
421    */
422   Synchronized& operator=(T&& rhs) {
423     auto guard = operator->();
424     datum_ = std::move(rhs);
425     return *this;
426   }
427
428   /**
429    * Acquire an appropriate lock based on the context.
430    *
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.
433    *
434    * In general, prefer using the explicit rlock() and wlock() methods
435    * for read-write locks, and lock() for purely exclusive locks.
436    *
437    * contextualLock() is primarily intended for use in other template functions
438    * that do not necessarily know the lock type.
439    */
440   LockedPtr contextualLock() {
441     return LockedPtr(this);
442   }
443   ConstLockedPtr contextualLock() const {
444     return ConstLockedPtr(this);
445   }
446   template <class Rep, class Period>
447   LockedPtr contextualLock(const std::chrono::duration<Rep, Period>& timeout) {
448     return LockedPtr(this, timeout);
449   }
450   template <class Rep, class Period>
451   ConstLockedPtr contextualLock(
452       const std::chrono::duration<Rep, Period>& timeout) const {
453     return ConstLockedPtr(this, timeout);
454   }
455   /**
456    * contextualRLock() acquires a read lock if the mutex type is shared,
457    * or a regular exclusive lock for non-shared mutex types.
458    *
459    * contextualRLock() when you know that you prefer a read lock (if
460    * available), even if the Synchronized<T> object itself is non-const.
461    */
462   ConstLockedPtr contextualRLock() const {
463     return ConstLockedPtr(this);
464   }
465   template <class Rep, class Period>
466   ConstLockedPtr contextualRLock(
467       const std::chrono::duration<Rep, Period>& timeout) const {
468     return ConstLockedPtr(this, timeout);
469   }
470
471   /**
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.
476    *
477    * NOTE: This API is planned to be deprecated in an upcoming diff.
478    * Prefer using lock(), wlock(), or rlock() instead.
479    */
480   LockedPtr operator->() {
481     return LockedPtr(this);
482   }
483
484   /**
485    * Obtain a ConstLockedPtr.
486    *
487    * NOTE: This API is planned to be deprecated in an upcoming diff.
488    * Prefer using lock(), wlock(), or rlock() instead.
489    */
490   ConstLockedPtr operator->() const {
491     return ConstLockedPtr(this);
492   }
493
494   /**
495    * Attempts to acquire for a given number of milliseconds. If
496    * acquisition is unsuccessful, the returned LockedPtr is NULL.
497    *
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.
501    */
502   LockedPtr timedAcquire(unsigned int milliseconds) {
503     return LockedPtr(this, std::chrono::milliseconds(milliseconds));
504   }
505
506   /**
507    * Attempts to acquire for a given number of milliseconds. If
508    * acquisition is unsuccessful, the returned ConstLockedPtr is NULL.
509    *
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.
513    */
514   ConstLockedPtr timedAcquire(unsigned int milliseconds) const {
515     return ConstLockedPtr(this, std::chrono::milliseconds(milliseconds));
516   }
517
518   /**
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().
523    *
524    * NOTE: This API is planned to be deprecated in an upcoming diff.
525    * Use rlock() instead.
526    */
527   const Synchronized& asConst() const {
528     return *this;
529   }
530
531   /**
532    * Swaps with another Synchronized. Protected against
533    * self-swap. Only data is swapped. Locks are acquired in increasing
534    * address order.
535    */
536   void swap(Synchronized& rhs) {
537     if (this == &rhs) {
538       return;
539     }
540     if (this > &rhs) {
541       return rhs.swap(*this);
542     }
543     auto guard1 = operator->();
544     auto guard2 = rhs.operator->();
545
546     using std::swap;
547     swap(datum_, rhs.datum_);
548   }
549
550   /**
551    * Swap with another datum. Recommended because it keeps the mutex
552    * held only briefly.
553    */
554   void swap(T& rhs) {
555     LockedPtr guard(this);
556
557     using std::swap;
558     swap(datum_, rhs);
559   }
560
561   /**
562    * Copies datum to a given target.
563    */
564   void copy(T* target) const {
565     ConstLockedPtr guard(this);
566     *target = datum_;
567   }
568
569   /**
570    * Returns a fresh copy of the datum.
571    */
572   T copy() const {
573     ConstLockedPtr guard(this);
574     return datum_;
575   }
576
577  private:
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;
584
585   /**
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
590    */
591   Synchronized(
592       const Synchronized& rhs,
593       const ConstLockedPtr& /*guard*/) noexcept(nxCopyCtor)
594       : datum_(rhs.datum_) {}
595
596   Synchronized(Synchronized&& rhs, const LockedPtr& /*guard*/) noexcept(
597       nxMoveCtor)
598       : datum_(std::move(rhs.datum_)) {}
599
600   // Synchronized data members
601   T datum_;
602   mutable Mutex mutex_;
603 };
604
605 template <class SynchronizedType, class LockPolicy>
606 class ScopedUnlocker;
607
608 namespace detail {
609 /*
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.
612  */
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;
618 /*
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.
621  */
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;
627 } // detail
628
629 /**
630  * A helper base class for implementing LockedPtr.
631  *
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>.
636  *
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.
643  *
644  * Note that the SynchronizedType template parameter may or may not be const
645  * qualified.
646  */
647 template <class SynchronizedType, class Mutex, class LockPolicy>
648 class LockedPtrBase {
649  public:
650   using MutexType = Mutex;
651   friend class folly::ScopedUnlocker<SynchronizedType, LockPolicy>;
652
653   /**
654    * Destructor releases.
655    */
656   ~LockedPtrBase() {
657     if (parent_) {
658       LockPolicy::unlock(parent_->mutex_);
659     }
660   }
661
662   /**
663    * Unlock the synchronized data.
664    *
665    * The LockedPtr can no longer be dereferenced after unlock() has been
666    * called.  isValid() will return false on an unlocked LockedPtr.
667    *
668    * unlock() can only be called on a LockedPtr that is valid.
669    */
670   void unlock() {
671     DCHECK(parent_ != nullptr);
672     LockPolicy::unlock(parent_->mutex_);
673     parent_ = nullptr;
674   }
675
676  protected:
677   LockedPtrBase() {}
678   explicit LockedPtrBase(SynchronizedType* parent) : parent_(parent) {
679     LockPolicy::lock(parent_->mutex_);
680   }
681   template <class Rep, class Period>
682   LockedPtrBase(
683       SynchronizedType* parent,
684       const std::chrono::duration<Rep, Period>& timeout) {
685     if (LockPolicy::try_lock_for(parent->mutex_, timeout)) {
686       this->parent_ = parent;
687     }
688   }
689   LockedPtrBase(LockedPtrBase&& rhs) noexcept : parent_(rhs.parent_) {
690     rhs.parent_ = nullptr;
691   }
692   LockedPtrBase& operator=(LockedPtrBase&& rhs) noexcept {
693     if (parent_) {
694       LockPolicy::unlock(parent_->mutex_);
695     }
696
697     parent_ = rhs.parent_;
698     rhs.parent_ = nullptr;
699     return *this;
700   }
701
702   using UnlockerData = SynchronizedType*;
703
704   /**
705    * Get a pointer to the Synchronized object from the UnlockerData.
706    *
707    * In the generic case UnlockerData is just the Synchronized pointer,
708    * so we return it as is.  (This function is more interesting in the
709    * std::mutex specialization below.)
710    */
711   static SynchronizedType* getSynchronized(UnlockerData data) {
712     return data;
713   }
714
715   UnlockerData releaseLock() {
716     DCHECK(parent_ != nullptr);
717     auto current = parent_;
718     parent_ = nullptr;
719     LockPolicy::unlock(current->mutex_);
720     return current;
721   }
722   void reacquireLock(UnlockerData&& data) {
723     DCHECK(parent_ == nullptr);
724     parent_ = data;
725     LockPolicy::lock(parent_->mutex_);
726   }
727
728   SynchronizedType* parent_ = nullptr;
729 };
730
731 /**
732  * LockedPtrBase specialization for use with std::mutex.
733  *
734  * When std::mutex is used we use a std::unique_lock to hold the mutex.
735  * This makes it possible to use std::condition_variable with a
736  * Synchronized<T, std::mutex>.
737  */
738 template <class SynchronizedType, class LockPolicy>
739 class LockedPtrBase<SynchronizedType, std::mutex, LockPolicy> {
740  public:
741   using MutexType = std::mutex;
742   friend class folly::ScopedUnlocker<SynchronizedType, LockPolicy>;
743
744   /**
745    * Destructor releases.
746    */
747   ~LockedPtrBase() {
748     // The std::unique_lock will automatically release the lock when it is
749     // destroyed, so we don't need to do anything extra here.
750   }
751
752   LockedPtrBase(LockedPtrBase&& rhs) noexcept
753       : lock_(std::move(rhs.lock_)), parent_(rhs.parent_) {
754     rhs.parent_ = nullptr;
755   }
756   LockedPtrBase& operator=(LockedPtrBase&& rhs) noexcept {
757     lock_ = std::move(rhs.lock_);
758     parent_ = rhs.parent_;
759     rhs.parent_ = nullptr;
760     return *this;
761   }
762
763   /**
764    * Get a reference to the std::unique_lock.
765    *
766    * This is provided so that callers can use Synchronized<T, std::mutex>
767    * with a std::condition_variable.
768    *
769    * While this API could be used to bypass the normal Synchronized APIs and
770    * manually interact with the underlying unique_lock, this is strongly
771    * discouraged.
772    */
773   std::unique_lock<std::mutex>& getUniqueLock() {
774     return lock_;
775   }
776
777   /**
778    * Unlock the synchronized data.
779    *
780    * The LockedPtr can no longer be dereferenced after unlock() has been
781    * called.  isValid() will return false on an unlocked LockedPtr.
782    *
783    * unlock() can only be called on a LockedPtr that is valid.
784    */
785   void unlock() {
786     DCHECK(parent_ != nullptr);
787     lock_.unlock();
788     parent_ = nullptr;
789   }
790
791  protected:
792   LockedPtrBase() {}
793   explicit LockedPtrBase(SynchronizedType* parent)
794       : lock_(parent->mutex_), parent_(parent) {}
795
796   using UnlockerData =
797       std::pair<std::unique_lock<std::mutex>, SynchronizedType*>;
798
799   static SynchronizedType* getSynchronized(const UnlockerData& data) {
800     return data.second;
801   }
802
803   UnlockerData releaseLock() {
804     DCHECK(parent_ != nullptr);
805     UnlockerData data(std::move(lock_), parent_);
806     parent_ = nullptr;
807     data.first.unlock();
808     return data;
809   }
810   void reacquireLock(UnlockerData&& data) {
811     lock_ = std::move(data.first);
812     lock_.lock();
813     parent_ = data.second;
814   }
815
816   // The specialization for std::mutex does have to store slightly more
817   // state than the default implementation.
818   std::unique_lock<std::mutex> lock_;
819   SynchronizedType* parent_ = nullptr;
820 };
821
822 /**
823  * This class temporarily unlocks a LockedPtr in a scoped manner.
824  */
825 template <class SynchronizedType, class LockPolicy>
826 class ScopedUnlocker {
827  public:
828   explicit ScopedUnlocker(LockedPtr<SynchronizedType, LockPolicy>* p)
829       : ptr_(p), data_(ptr_->releaseLock()) {}
830   ScopedUnlocker(const ScopedUnlocker&) = delete;
831   ScopedUnlocker& operator=(const ScopedUnlocker&) = delete;
832   ScopedUnlocker(ScopedUnlocker&& other) noexcept
833       : ptr_(other.ptr_), data_(std::move(other.data_)) {
834     other.ptr_ = nullptr;
835   }
836   ScopedUnlocker& operator=(ScopedUnlocker&& other) = delete;
837
838   ~ScopedUnlocker() {
839     if (ptr_) {
840       ptr_->reacquireLock(std::move(data_));
841     }
842   }
843
844   /**
845    * Return a pointer to the Synchronized object used by this ScopedUnlocker.
846    */
847   SynchronizedType* getSynchronized() const {
848     return LockedPtr<SynchronizedType, LockPolicy>::getSynchronized(data_);
849   }
850
851  private:
852   using Data = typename LockedPtr<SynchronizedType, LockPolicy>::UnlockerData;
853   LockedPtr<SynchronizedType, LockPolicy>* ptr_{nullptr};
854   Data data_;
855 };
856
857 /**
858  * A LockedPtr keeps a Synchronized<T> object locked for the duration of
859  * LockedPtr's existence.
860  *
861  * It provides access the datum's members directly by using operator->() and
862  * operator*().
863  *
864  * The LockPolicy parameter controls whether or not the lock is acquired in
865  * exclusive or shared mode.
866  */
867 template <class SynchronizedType, class LockPolicy>
868 class LockedPtr : public LockedPtrBase<
869                       SynchronizedType,
870                       typename SynchronizedType::MutexType,
871                       LockPolicy> {
872  private:
873   using Base = LockedPtrBase<
874       SynchronizedType,
875       typename SynchronizedType::MutexType,
876       LockPolicy>;
877   using UnlockerData = typename Base::UnlockerData;
878   // CDataType is the DataType with the appropriate const-qualification
879   using CDataType = detail::SynchronizedDataType<SynchronizedType>;
880
881  public:
882   using DataType = typename SynchronizedType::DataType;
883   using MutexType = typename SynchronizedType::MutexType;
884   using Synchronized = typename std::remove_const<SynchronizedType>::type;
885   friend class ScopedUnlocker<SynchronizedType, LockPolicy>;
886
887   /**
888    * Creates an uninitialized LockedPtr.
889    *
890    * Dereferencing an uninitialized LockedPtr is not allowed.
891    */
892   LockedPtr() {}
893
894   /**
895    * Takes a Synchronized<T> and locks it.
896    */
897   explicit LockedPtr(SynchronizedType* parent) : Base(parent) {}
898
899   /**
900    * Takes a Synchronized<T> and attempts to lock it, within the specified
901    * timeout.
902    *
903    * Blocks until the lock is acquired or until the specified timeout expires.
904    * If the timeout expired without acquiring the lock, the LockedPtr will be
905    * null, and LockedPtr::isNull() will return true.
906    */
907   template <class Rep, class Period>
908   LockedPtr(
909       SynchronizedType* parent,
910       const std::chrono::duration<Rep, Period>& timeout)
911       : Base(parent, timeout) {}
912
913   /**
914    * Move constructor.
915    */
916   LockedPtr(LockedPtr&& rhs) noexcept = default;
917
918   /**
919    * Move assignment operator.
920    */
921   LockedPtr& operator=(LockedPtr&& rhs) noexcept = default;
922
923   /*
924    * Copy constructor and assignment operator are deleted.
925    */
926   LockedPtr(const LockedPtr& rhs) = delete;
927   LockedPtr& operator=(const LockedPtr& rhs) = delete;
928
929   /**
930    * Destructor releases.
931    */
932   ~LockedPtr() {}
933
934   /**
935    * Check if this LockedPtr is uninitialized, or points to valid locked data.
936    *
937    * This method can be used to check if a timed-acquire operation succeeded.
938    * If an acquire operation times out it will result in a null LockedPtr.
939    *
940    * A LockedPtr is always either null, or holds a lock to valid data.
941    * Methods such as scopedUnlock() reset the LockedPtr to null for the
942    * duration of the unlock.
943    */
944   bool isNull() const {
945     return this->parent_ == nullptr;
946   }
947
948   /**
949    * Explicit boolean conversion.
950    *
951    * Returns !isNull()
952    */
953   explicit operator bool() const {
954     return this->parent_ != nullptr;
955   }
956
957   /**
958    * Access the locked data.
959    *
960    * This method should only be used if the LockedPtr is valid.
961    */
962   CDataType* operator->() const {
963     return &this->parent_->datum_;
964   }
965
966   /**
967    * Access the locked data.
968    *
969    * This method should only be used if the LockedPtr is valid.
970    */
971   CDataType& operator*() const {
972     return this->parent_->datum_;
973   }
974
975   /**
976    * Temporarily unlock the LockedPtr, and reset it to null.
977    *
978    * Returns an helper object that will re-lock and restore the LockedPtr when
979    * the helper is destroyed.  The LockedPtr may not be dereferenced for as
980    * long as this helper object exists.
981    */
982   ScopedUnlocker<SynchronizedType, LockPolicy> scopedUnlock() {
983     return ScopedUnlocker<SynchronizedType, LockPolicy>(this);
984   }
985 };
986
987 /**
988  * LockedGuardPtr is a simplified version of LockedPtr.
989  *
990  * It is non-movable, and supports fewer features than LockedPtr.  However, it
991  * is ever-so-slightly more performant than LockedPtr.  (The destructor can
992  * unconditionally release the lock, without requiring a conditional branch.)
993  *
994  * The relationship between LockedGuardPtr and LockedPtr is similar to that
995  * between std::lock_guard and std::unique_lock.
996  */
997 template <class SynchronizedType, class LockPolicy>
998 class LockedGuardPtr {
999  private:
1000   // CDataType is the DataType with the appropriate const-qualification
1001   using CDataType = detail::SynchronizedDataType<SynchronizedType>;
1002
1003  public:
1004   using DataType = typename SynchronizedType::DataType;
1005   using MutexType = typename SynchronizedType::MutexType;
1006   using Synchronized = typename std::remove_const<SynchronizedType>::type;
1007
1008   LockedGuardPtr() = delete;
1009
1010   /**
1011    * Takes a Synchronized<T> and locks it.
1012    */
1013   explicit LockedGuardPtr(SynchronizedType* parent) : parent_(parent) {
1014     LockPolicy::lock(parent_->mutex_);
1015   }
1016
1017   /**
1018    * Destructor releases.
1019    */
1020   ~LockedGuardPtr() {
1021     LockPolicy::unlock(parent_->mutex_);
1022   }
1023
1024   /**
1025    * Access the locked data.
1026    */
1027   CDataType* operator->() const {
1028     return &parent_->datum_;
1029   }
1030
1031   /**
1032    * Access the locked data.
1033    */
1034   CDataType& operator*() const {
1035     return parent_->datum_;
1036   }
1037
1038  private:
1039   // This is the entire state of LockedGuardPtr.
1040   SynchronizedType* const parent_{nullptr};
1041 };
1042
1043 /**
1044  * Acquire locks for multiple Synchronized<T> objects, in a deadlock-safe
1045  * manner.
1046  *
1047  * The locks are acquired in order from lowest address to highest address.
1048  * (Note that this is not necessarily the same algorithm used by std::lock().)
1049  *
1050  * For parameters that are const and support shared locks, a read lock is
1051  * acquired.  Otherwise an exclusive lock is acquired.
1052  *
1053  * TODO: Extend acquireLocked() with variadic template versions that
1054  * allow for more than 2 Synchronized arguments.  (I haven't given too much
1055  * thought about how to implement this.  It seems like it would be rather
1056  * complicated, but I think it should be possible.)
1057  */
1058 template <class Sync1, class Sync2>
1059 std::tuple<detail::LockedPtrType<Sync1>, detail::LockedPtrType<Sync2>>
1060 acquireLocked(Sync1& l1, Sync2& l2) {
1061   if (static_cast<const void*>(&l1) < static_cast<const void*>(&l2)) {
1062     auto p1 = l1.contextualLock();
1063     auto p2 = l2.contextualLock();
1064     return std::make_tuple(std::move(p1), std::move(p2));
1065   } else {
1066     auto p2 = l2.contextualLock();
1067     auto p1 = l1.contextualLock();
1068     return std::make_tuple(std::move(p1), std::move(p2));
1069   }
1070 }
1071
1072 /**
1073  * A version of acquireLocked() that returns a std::pair rather than a
1074  * std::tuple, which is easier to use in many places.
1075  */
1076 template <class Sync1, class Sync2>
1077 std::pair<detail::LockedPtrType<Sync1>, detail::LockedPtrType<Sync2>>
1078 acquireLockedPair(Sync1& l1, Sync2& l2) {
1079   auto lockedPtrs = acquireLocked(l1, l2);
1080   return {std::move(std::get<0>(lockedPtrs)),
1081           std::move(std::get<1>(lockedPtrs))};
1082 }
1083
1084 /************************************************************************
1085  * NOTE: All APIs below this line will be deprecated in upcoming diffs.
1086  ************************************************************************/
1087
1088 // Non-member swap primitive
1089 template <class T, class M>
1090 void swap(Synchronized<T, M>& lhs, Synchronized<T, M>& rhs) {
1091   lhs.swap(rhs);
1092 }
1093
1094 /**
1095  * SYNCHRONIZED is the main facility that makes Synchronized<T>
1096  * helpful. It is a pseudo-statement that introduces a scope where the
1097  * object is locked. Inside that scope you get to access the unadorned
1098  * datum.
1099  *
1100  * Example:
1101  *
1102  * Synchronized<vector<int>> svector;
1103  * ...
1104  * SYNCHRONIZED (svector) { ... use svector as a vector<int> ... }
1105  * or
1106  * SYNCHRONIZED (v, svector) { ... use v as a vector<int> ... }
1107  *
1108  * Refer to folly/docs/Synchronized.md for a detailed explanation and more
1109  * examples.
1110  */
1111 #define SYNCHRONIZED(...)                                             \
1112   FOLLY_PUSH_WARNING                                                  \
1113   FOLLY_GCC_DISABLE_WARNING(shadow)                                   \
1114   if (bool SYNCHRONIZED_state = false) {                              \
1115   } else                                                              \
1116     for (auto SYNCHRONIZED_lockedPtr =                                \
1117              (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).operator->(); \
1118          !SYNCHRONIZED_state;                                         \
1119          SYNCHRONIZED_state = true)                                   \
1120       for (auto& FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)) =                \
1121                *SYNCHRONIZED_lockedPtr.operator->();                  \
1122            !SYNCHRONIZED_state;                                       \
1123            SYNCHRONIZED_state = true)                                 \
1124   FOLLY_POP_WARNING
1125
1126 #define TIMED_SYNCHRONIZED(timeout, ...)                                       \
1127   if (bool SYNCHRONIZED_state = false) {                                       \
1128   } else                                                                       \
1129     for (auto SYNCHRONIZED_lockedPtr =                                         \
1130              (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).timedAcquire(timeout); \
1131          !SYNCHRONIZED_state;                                                  \
1132          SYNCHRONIZED_state = true)                                            \
1133       for (auto FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)) =                          \
1134                (!SYNCHRONIZED_lockedPtr                                        \
1135                     ? nullptr                                                  \
1136                     : SYNCHRONIZED_lockedPtr.operator->());                    \
1137            !SYNCHRONIZED_state;                                                \
1138            SYNCHRONIZED_state = true)
1139
1140 /**
1141  * Similar to SYNCHRONIZED, but only uses a read lock.
1142  */
1143 #define SYNCHRONIZED_CONST(...)            \
1144   SYNCHRONIZED(                            \
1145       FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)), \
1146       (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).asConst())
1147
1148 /**
1149  * Similar to TIMED_SYNCHRONIZED, but only uses a read lock.
1150  */
1151 #define TIMED_SYNCHRONIZED_CONST(timeout, ...) \
1152   TIMED_SYNCHRONIZED(                          \
1153       timeout,                                 \
1154       FB_VA_GLUE(FB_ARG_1, (__VA_ARGS__)),     \
1155       (FB_VA_GLUE(FB_ARG_2_OR_1, (__VA_ARGS__))).asConst())
1156
1157 /**
1158  * Temporarily disables synchronization inside a SYNCHRONIZED block.
1159  *
1160  * Note: This macro is deprecated, and kind of broken.  The input parameter
1161  * does not control what it unlocks--it always unlocks the lock acquired by the
1162  * most recent SYNCHRONIZED scope.  If you have two nested SYNCHRONIZED blocks,
1163  * UNSYNCHRONIZED always unlocks the inner-most, even if you pass in the
1164  * variable name used in the outer SYNCHRONIZED block.
1165  *
1166  * This macro will be removed soon in a subsequent diff.
1167  */
1168 #define UNSYNCHRONIZED(name)                                             \
1169   for (auto SYNCHRONIZED_state3 = SYNCHRONIZED_lockedPtr.scopedUnlock(); \
1170        !SYNCHRONIZED_state;                                              \
1171        SYNCHRONIZED_state = true)                                        \
1172     for (auto& name = *SYNCHRONIZED_state3.getSynchronized();            \
1173          !SYNCHRONIZED_state;                                            \
1174          SYNCHRONIZED_state = true)
1175
1176 /**
1177  * Synchronizes two Synchronized objects (they may encapsulate
1178  * different data). Synchronization is done in increasing address of
1179  * object order, so there is no deadlock risk.
1180  */
1181 #define SYNCHRONIZED_DUAL(n1, e1, n2, e2)                               \
1182   if (bool SYNCHRONIZED_state = false) {                                \
1183   } else                                                                \
1184     for (auto SYNCHRONIZED_ptrs = acquireLockedPair(e1, e2);            \
1185          !SYNCHRONIZED_state;                                           \
1186          SYNCHRONIZED_state = true)                                     \
1187       for (auto& n1 = *SYNCHRONIZED_ptrs.first; !SYNCHRONIZED_state;    \
1188            SYNCHRONIZED_state = true)                                   \
1189         for (auto& n2 = *SYNCHRONIZED_ptrs.second; !SYNCHRONIZED_state; \
1190              SYNCHRONIZED_state = true)
1191
1192 } /* namespace folly */