]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/gwp_asan/mutex.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / gwp_asan / mutex.h
1 //===-- mutex.h -------------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef GWP_ASAN_MUTEX_H_
10 #define GWP_ASAN_MUTEX_H_
11
12 #ifdef __unix__
13 #include <pthread.h>
14 #else
15 #error "GWP-ASan is not supported on this platform."
16 #endif
17
18 namespace gwp_asan {
19 class Mutex {
20 public:
21   constexpr Mutex() = default;
22   ~Mutex() = default;
23   Mutex(const Mutex &) = delete;
24   Mutex &operator=(const Mutex &) = delete;
25   // Lock the mutex.
26   void lock();
27   // Nonblocking trylock of the mutex. Returns true if the lock was acquired.
28   bool tryLock();
29   // Unlock the mutex.
30   void unlock();
31
32 private:
33 #ifdef __unix__
34   pthread_mutex_t Mu = PTHREAD_MUTEX_INITIALIZER;
35 #endif // defined(__unix__)
36 };
37
38 class ScopedLock {
39 public:
40   explicit ScopedLock(Mutex &Mx) : Mu(Mx) { Mu.lock(); }
41   ~ScopedLock() { Mu.unlock(); }
42   ScopedLock(const ScopedLock &) = delete;
43   ScopedLock &operator=(const ScopedLock &) = delete;
44
45 private:
46   Mutex &Mu;
47 };
48 } // namespace gwp_asan
49
50 #endif // GWP_ASAN_MUTEX_H_