• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_MAY_AUTO_LOCK_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_MAY_AUTO_LOCK_H_
7 
8 #include "base/component_export.h"
9 #include "base/macros.h"
10 #include "base/optional.h"
11 #include "base/synchronization/lock.h"
12 
13 namespace mojo {
14 namespace internal {
15 
16 // Similar to base::AutoLock, except that it does nothing if |lock| passed into
17 // the constructor is null.
COMPONENT_EXPORT(MOJO_CPP_BINDINGS_BASE)18 class COMPONENT_EXPORT(MOJO_CPP_BINDINGS_BASE) MayAutoLock {
19  public:
20   explicit MayAutoLock(base::Optional<base::Lock>* lock)
21       : lock_(lock->has_value() ? &lock->value() : nullptr) {
22     if (lock_)
23       lock_->Acquire();
24   }
25 
26   ~MayAutoLock() {
27     if (lock_) {
28       lock_->AssertAcquired();
29       lock_->Release();
30     }
31   }
32 
33  private:
34   base::Lock* lock_;
35   DISALLOW_COPY_AND_ASSIGN(MayAutoLock);
36 };
37 
38 // Similar to base::AutoUnlock, except that it does nothing if |lock| passed
39 // into the constructor is null.
COMPONENT_EXPORT(MOJO_CPP_BINDINGS_BASE)40 class COMPONENT_EXPORT(MOJO_CPP_BINDINGS_BASE) MayAutoUnlock {
41  public:
42   explicit MayAutoUnlock(base::Optional<base::Lock>* lock)
43       : lock_(lock->has_value() ? &lock->value() : nullptr) {
44     if (lock_) {
45       lock_->AssertAcquired();
46       lock_->Release();
47     }
48   }
49 
50   ~MayAutoUnlock() {
51     if (lock_)
52       lock_->Acquire();
53   }
54 
55  private:
56   base::Lock* lock_;
57   DISALLOW_COPY_AND_ASSIGN(MayAutoUnlock);
58 };
59 
60 }  // namespace internal
61 }  // namespace mojo
62 
63 #endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_MAY_AUTO_LOCK_H_
64