1 // Copyright (C) 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef ICING_ABSL_PORTS_MUTEX_H_
16 #define ICING_ABSL_PORTS_MUTEX_H_
17 
18 #include <mutex>         // NOLINT
19 #include <shared_mutex>  // NOLINT
20 
21 #include "icing/absl_ports/thread_annotations.h"
22 
23 namespace icing {
24 namespace lib {
25 namespace absl_ports {
26 
27 // Simple wrapper around std::shared_mutex with annotations to allow thread
28 // annotation checks.
29 class ICING_LOCKABLE shared_mutex {
30  public:
lock()31   void lock() ICING_EXCLUSIVE_LOCK_FUNCTION() { m_.lock(); }
try_lock()32   bool try_lock() ICING_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
33     return m_.try_lock();
34   }
unlock()35   void unlock() ICING_UNLOCK_FUNCTION() { m_.unlock(); }
36 
lock_shared()37   void lock_shared() ICING_SHARED_LOCK_FUNCTION() { m_.lock_shared(); }
try_lock_shared()38   bool try_lock_shared() ICING_SHARED_TRYLOCK_FUNCTION(true) {
39     return m_.try_lock_shared();
40   }
unlock_shared()41   void unlock_shared() ICING_UNLOCK_FUNCTION() { m_.unlock_shared(); }
42 
43  private:
44   std::shared_mutex m_;
45 };
46 
47 // Simple wrapper around std::unique_lock with annotations to allow thread
48 // annotation checks.
49 class ICING_SCOPED_LOCKABLE unique_lock {
50  public:
unique_lock(shared_mutex * mu)51   explicit unique_lock(shared_mutex* mu) ICING_EXCLUSIVE_LOCK_FUNCTION(mu)
52       : lock_(*mu) {}
53   ~unique_lock() ICING_UNLOCK_FUNCTION() = default;
54 
55  private:
56   std::unique_lock<shared_mutex> lock_;
57 };
58 
59 // Simple wrapper around std::shared_lock with annotations to allow thread
60 // annotation checks.
61 class ICING_SCOPED_LOCKABLE shared_lock {
62  public:
shared_lock(shared_mutex * mu)63   explicit shared_lock(shared_mutex* mu) ICING_SHARED_LOCK_FUNCTION(mu)
64       : lock_(*mu) {}
65   ~shared_lock() ICING_UNLOCK_FUNCTION() = default;
66 
67  private:
68   std::shared_lock<shared_mutex> lock_;
69 };
70 
71 }  // namespace absl_ports
72 }  // namespace lib
73 }  // namespace icing
74 
75 #endif  // ICING_ABSL_PORTS_MUTEX_H_
76