Debian Codegraph @

Xpjproject/third_party/webrtc_aec3/src/rtc_base/synchronization/mutex_race_check.h

raw symbols SCIP
1 /*
2 * Copyright 2020 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #ifndef RTC_BASE_SYNCHRONIZATION_MUTEX_RACE_CHECK_H_
12 #define RTC_BASE_SYNCHRONIZATION_MUTEX_RACE_CHECK_H_
13
14 #include <atomic>
15
16 #include "rtc_base/checks.h"
17 #include "rtc_base/system/unused.h"
18 #include "rtc_base/thread_annotations.h"
19
20 namespace webrtc {
21
22 // This implementation class is useful when a consuming project can guarantee
23 // that all WebRTC invocation is happening serially. Additionally, the consuming
24 // project cannot use WebRTC code that spawn threads or task queues.
25 //
26 // The class internally check fails on Lock() if it finds the consumer actually
27 // invokes WebRTC concurrently.
28 //
29 // To use the race check mutex, define WEBRTC_RACE_CHECK_MUTEX globally. This
30 // also adds a dependency to absl::Mutex from logging.cc because even though
31 // objects are invoked serially, the logging is static and invoked concurrently
32 // and hence needs protection.
33 class RTC_LOCKABLE MutexImpl final {
34 public:
35 MutexImpl() = default;
36 MutexImpl(const MutexImpl&) = delete;
37 MutexImpl& operator=(const MutexImpl&) = delete;
38
39 void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() {
40 bool was_free = free_.exchange(false, std::memory_order_acquire);
41 RTC_CHECK(was_free)
42 << "WEBRTC_RACE_CHECK_MUTEX: mutex locked concurrently.";
43 }
44 RTC_WARN_UNUSED_RESULT bool TryLock() RTC_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
45 bool was_free = free_.exchange(false, std::memory_order_acquire);
46 return was_free;
47 }
48 void Unlock() RTC_UNLOCK_FUNCTION() {
49 free_.store(true, std::memory_order_release);
50 }
51
52 private:
53 // Release-acquire ordering is used.
54 // - In the Lock methods we're guaranteeing that reads and writes happening
55 // after the (Try)Lock don't appear to have happened before the Lock (acquire
56 // ordering).
57 // - In the Unlock method we're guaranteeing that reads and writes happening
58 // before the Unlock don't appear to happen after it (release ordering).
59 std::atomic<bool> free_{true};
60 };
61
62 } // namespace webrtc
63
64 #endif // RTC_BASE_SYNCHRONIZATION_MUTEX_RACE_CHECK_H_