libcamera  v0.3.1+1-c9152bad
Supporting cameras in Linux since 2019
mutex.h
Go to the documentation of this file.
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /*
3  * Copyright (C) 2021, Google Inc.
4  *
5  * Mutex classes with clang thread safety annotation
6  */
7 
8 #pragma once
9 
10 #include <condition_variable>
11 #include <mutex>
12 
13 #include <libcamera/base/private.h>
14 
15 #include <libcamera/base/thread_annotations.h>
16 
17 namespace libcamera {
18 
19 /* \todo using Mutex = std::mutex if libc++ is used. */
20 
21 #ifndef __DOXYGEN__
22 
23 class LIBCAMERA_TSA_CAPABILITY("mutex") Mutex final
24 {
25 public:
26  constexpr Mutex()
27  {
28  }
29 
30  void lock() LIBCAMERA_TSA_ACQUIRE()
31  {
32  mutex_.lock();
33  }
34 
35  void unlock() LIBCAMERA_TSA_RELEASE()
36  {
37  mutex_.unlock();
38  }
39 
40 private:
41  friend class MutexLocker;
42 
43  std::mutex mutex_;
44 };
45 
46 class LIBCAMERA_TSA_SCOPED_CAPABILITY MutexLocker final
47 {
48 public:
49  explicit MutexLocker(Mutex &mutex) LIBCAMERA_TSA_ACQUIRE(mutex)
50  : lock_(mutex.mutex_)
51  {
52  }
53 
54  MutexLocker(Mutex &mutex, std::defer_lock_t t) noexcept LIBCAMERA_TSA_EXCLUDES(mutex)
55  : lock_(mutex.mutex_, t)
56  {
57  }
58 
59  ~MutexLocker() LIBCAMERA_TSA_RELEASE()
60  {
61  }
62 
63  void lock() LIBCAMERA_TSA_ACQUIRE()
64  {
65  lock_.lock();
66  }
67 
68  bool try_lock() LIBCAMERA_TSA_TRY_ACQUIRE(true)
69  {
70  return lock_.try_lock();
71  }
72 
73  void unlock() LIBCAMERA_TSA_RELEASE()
74  {
75  lock_.unlock();
76  }
77 
78 private:
79  friend class ConditionVariable;
80 
81  std::unique_lock<std::mutex> lock_;
82 };
83 
84 class ConditionVariable final
85 {
86 public:
87  ConditionVariable()
88  {
89  }
90 
91  void notify_one() noexcept
92  {
93  cv_.notify_one();
94  }
95 
96  void notify_all() noexcept
97  {
98  cv_.notify_all();
99  }
100 
101  template<class Predicate>
102  void wait(MutexLocker &locker, Predicate stopWaiting)
103  {
104  cv_.wait(locker.lock_, stopWaiting);
105  }
106 
107  template<class Rep, class Period, class Predicate>
108  bool wait_for(MutexLocker &locker,
109  const std::chrono::duration<Rep, Period> &relTime,
110  Predicate stopWaiting)
111  {
112  return cv_.wait_for(locker.lock_, relTime, stopWaiting);
113  }
114 
115 private:
116  std::condition_variable cv_;
117 };
118 
119 #else /* __DOXYGEN__ */
120 
121 class Mutex final
122 {
123 };
124 
125 class MutexLocker final
126 {
127 };
128 
129 class ConditionVariable final
130 {
131 };
132 
133 #endif /* __DOXYGEN__ */
134 } /* namespace libcamera */
std::mutex wrapper with clang thread safety annotation
Definition: mutex.h:121
Top-level libcamera namespace.
Definition: backtrace.h:17
std::unique_lock wrapper with clang thread safety annotation
Definition: mutex.h:125
std::condition_variable wrapper integrating with MutexLocker
Definition: mutex.h:129