1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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 #ifndef ANDROIDFW_MUTEXGUARD_H
18 #define ANDROIDFW_MUTEXGUARD_H
19 
20 #include <mutex>
21 #include <optional>
22 #include <type_traits>
23 
24 #include "android-base/macros.h"
25 
26 namespace android {
27 
28 template <typename T>
29 class ScopedLock;
30 
31 // Owns the guarded object and protects access to it via a mutex.
32 // The guarded object is inaccessible via this class.
33 // The mutex is locked and the object accessed via the ScopedLock<T> class.
34 //
35 // NOTE: The template parameter T should not be a raw pointer, since ownership
36 // is ambiguous and error-prone. Instead use an std::unique_ptr<>.
37 //
38 // Example use:
39 //
40 //   Guarded<std::string> shared_string("hello");
41 //   {
42 //     ScopedLock<std::string> locked_string(shared_string);
43 //     *locked_string += " world";
44 //   }
45 //
46 template <typename T>
47 class Guarded {
48   static_assert(!std::is_pointer<T>::value, "T must not be a raw pointer");
49 
50  public:
Guarded()51   Guarded() : guarded_(std::in_place, T()) {
52   }
53 
Guarded(const T & guarded)54   explicit Guarded(const T& guarded) : guarded_(std::in_place, guarded) {
55   }
56 
Guarded(T && guarded)57   explicit Guarded(T&& guarded) : guarded_(std::in_place, std::forward<T>(guarded)) {
58   }
59 
~Guarded()60   ~Guarded() {
61     std::lock_guard<std::mutex> scoped_lock(lock_);
62     guarded_.reset();
63   }
64 
65  private:
66   friend class ScopedLock<T>;
67   DISALLOW_COPY_AND_ASSIGN(Guarded);
68 
69   std::mutex lock_;
70   std::optional<T> guarded_;
71 };
72 
73 template <typename T>
74 class ScopedLock {
75  public:
ScopedLock(Guarded<T> & guarded)76   explicit ScopedLock(Guarded<T>& guarded) : lock_(guarded.lock_), guarded_(*guarded.guarded_) {
77   }
78 
79   T& operator*() {
80     return guarded_;
81   }
82 
83   T* operator->() {
84     return &guarded_;
85   }
86 
get()87   T* get() {
88     return &guarded_;
89   }
90 
91  private:
92   DISALLOW_COPY_AND_ASSIGN(ScopedLock);
93 
94   std::lock_guard<std::mutex> lock_;
95   T& guarded_;
96 };
97 
98 }  // namespace android
99 
100 #endif  // ANDROIDFW_MUTEXGUARD_H
101