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