* configure.ac: Change target-libasan to target-libsanitizer.
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_mutex.h
bloba38a49ae24295de5b376da986ee5785468ed1000
1 //===-- sanitizer_mutex.h ---------------------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of ThreadSanitizer/AddressSanitizer runtime.
9 //
10 //===----------------------------------------------------------------------===//
12 #ifndef SANITIZER_MUTEX_H
13 #define SANITIZER_MUTEX_H
15 #include "sanitizer_atomic.h"
16 #include "sanitizer_internal_defs.h"
17 #include "sanitizer_libc.h"
19 namespace __sanitizer {
21 class StaticSpinMutex {
22 public:
23 void Init() {
24 atomic_store(&state_, 0, memory_order_relaxed);
27 void Lock() {
28 if (atomic_exchange(&state_, 1, memory_order_acquire) == 0)
29 return;
30 LockSlow();
33 void Unlock() {
34 atomic_store(&state_, 0, memory_order_release);
37 private:
38 atomic_uint8_t state_;
40 void NOINLINE LockSlow() {
41 for (int i = 0;; i++) {
42 if (i < 10)
43 proc_yield(10);
44 else
45 internal_sched_yield();
46 if (atomic_load(&state_, memory_order_relaxed) == 0
47 && atomic_exchange(&state_, 1, memory_order_acquire) == 0)
48 return;
53 class SpinMutex : public StaticSpinMutex {
54 public:
55 SpinMutex() {
56 Init();
59 private:
60 SpinMutex(const SpinMutex&);
61 void operator=(const SpinMutex&);
64 template<typename MutexType>
65 class GenericScopedLock {
66 public:
67 explicit GenericScopedLock(MutexType *mu)
68 : mu_(mu) {
69 mu_->Lock();
72 ~GenericScopedLock() {
73 mu_->Unlock();
76 private:
77 MutexType *mu_;
79 GenericScopedLock(const GenericScopedLock&);
80 void operator=(const GenericScopedLock&);
83 template<typename MutexType>
84 class GenericScopedReadLock {
85 public:
86 explicit GenericScopedReadLock(MutexType *mu)
87 : mu_(mu) {
88 mu_->ReadLock();
91 ~GenericScopedReadLock() {
92 mu_->ReadUnlock();
95 private:
96 MutexType *mu_;
98 GenericScopedReadLock(const GenericScopedReadLock&);
99 void operator=(const GenericScopedReadLock&);
102 typedef GenericScopedLock<StaticSpinMutex> SpinMutexLock;
104 } // namespace __sanitizer
106 #endif // SANITIZER_MUTEX_H