blob: 15e1caa1b277d5a88f73377022710afaaff44b31 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
//===-- sanitizer_mutex.h ---------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
//
//===----------------------------------------------------------------------===//
#ifndef SANITIZER_MUTEX_H
#define SANITIZER_MUTEX_H
#include "sanitizer_atomic.h"
#include "sanitizer_internal_defs.h"
#include "sanitizer_libc.h"
namespace __sanitizer {
class StaticSpinMutex {
public:
void Init() {
atomic_store(&state_, 0, memory_order_relaxed);
}
void Lock() {
if (TryLock())
return;
LockSlow();
}
bool TryLock() {
return atomic_exchange(&state_, 1, memory_order_acquire) == 0;
}
void Unlock() {
atomic_store(&state_, 0, memory_order_release);
}
private:
atomic_uint8_t state_;
void NOINLINE LockSlow() {
for (int i = 0;; i++) {
if (i < 10)
proc_yield(10);
else
internal_sched_yield();
if (atomic_load(&state_, memory_order_relaxed) == 0
&& atomic_exchange(&state_, 1, memory_order_acquire) == 0)
return;
}
}
};
class SpinMutex : public StaticSpinMutex {
public:
SpinMutex() {
Init();
}
private:
SpinMutex(const SpinMutex&);
void operator=(const SpinMutex&);
};
class BlockingMutex {
public:
explicit BlockingMutex(LinkerInitialized);
void Lock();
void Unlock();
private:
uptr opaque_storage_[10];
};
template<typename MutexType>
class GenericScopedLock {
public:
explicit GenericScopedLock(MutexType *mu)
: mu_(mu) {
mu_->Lock();
}
~GenericScopedLock() {
mu_->Unlock();
}
private:
MutexType *mu_;
GenericScopedLock(const GenericScopedLock&);
void operator=(const GenericScopedLock&);
};
template<typename MutexType>
class GenericScopedReadLock {
public:
explicit GenericScopedReadLock(MutexType *mu)
: mu_(mu) {
mu_->ReadLock();
}
~GenericScopedReadLock() {
mu_->ReadUnlock();
}
private:
MutexType *mu_;
GenericScopedReadLock(const GenericScopedReadLock&);
void operator=(const GenericScopedReadLock&);
};
typedef GenericScopedLock<StaticSpinMutex> SpinMutexLock;
typedef GenericScopedLock<BlockingMutex> BlockingMutexLock;
} // namespace __sanitizer
#endif // SANITIZER_MUTEX_H
|