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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use super::*;
use core::fmt::Debug;
use core::hash::Hash;
/// Holds the lock for one tag in a `TagLockTable`. The tag is released and its
/// table entry reclaimed when the last clone of the guard drops.
#[derive(Clone, Debug)]
pub struct TagLockGuard<T>
where
T: Hash + Eq + Clone + Debug,
{
inner: Arc<TagLockGuardInner<T>>,
}
impl<T> TagLockGuard<T>
where
T: Hash + Eq + Clone + Debug,
{
/// The tag this guard holds.
#[must_use]
pub fn tag(&self) -> T {
self.inner.tag()
}
}
struct TagLockGuardInner<T>
where
T: Hash + Eq + Clone + Debug,
{
table: TagLockTable<T>,
tag: T,
guard: Option<ArcMutexGuard<RawMutex, ()>>,
}
impl<T> fmt::Debug for TagLockGuardInner<T>
where
T: Hash + Eq + Clone + Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TagLockGuardInner")
.field("tag", &self.tag)
.finish()
}
}
impl<T> TagLockGuardInner<T>
where
T: Hash + Eq + Clone + Debug,
{
fn new(table: TagLockTable<T>, tag: T, guard: ArcMutexGuard<RawMutex, ()>) -> Self {
Self {
table,
tag,
guard: Some(guard),
}
}
fn tag(&self) -> T {
self.tag.clone()
}
}
impl<T> Drop for TagLockGuardInner<T>
where
T: Hash + Eq + Clone + Debug,
{
fn drop(&mut self) {
let mut inner = self.table.inner.lock();
// Inform the table we're dropping this guard
let guards = {
// Get the table entry, it must exist since we have a guard locked
let entry = inner.table.get_mut(&self.tag).unwrap_or_log();
// Decrement the number of guards
entry.guards -= 1;
// Return the number of guards left
entry.guards
};
// If there are no guards left, we remove the tag from the table
if guards == 0 {
inner.table.remove(&self.tag).unwrap_or_log();
}
// Proceed with releasing guard, which may cause some concurrent tag lock to acquire
drop(self.guard.take());
}
}
#[derive(Clone, Debug)]
struct TagLockTableEntry {
mutex: Arc<Mutex<()>>,
guards: usize,
}
struct TagLockTableInner<T>
where
T: Hash + Eq + Clone + Debug,
{
table: HashMap<T, TagLockTableEntry>,
}
/// A table of mutexes keyed by tag. Locking a tag blocks only other lockers of
/// the same tag; distinct tags never contend. Entries are created on first lock
/// and removed when their last guard drops.
#[derive(Clone)]
pub struct TagLockTable<T>
where
T: Hash + Eq + Clone + Debug,
{
inner: Arc<Mutex<TagLockTableInner<T>>>,
}
impl<T> fmt::Debug for TagLockTable<T>
where
T: Hash + Eq + Clone + Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TagLockTable").finish()
}
}
impl<T> TagLockTable<T>
where
T: Hash + Eq + Clone + Debug,
{
/// Create an empty table.
#[must_use]
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(TagLockTableInner {
table: HashMap::new(),
})),
}
}
/// Whether no tags are currently locked.
#[must_use]
pub fn is_empty(&self) -> bool {
let inner = self.inner.lock();
inner.table.is_empty()
}
/// Number of tags currently locked.
#[must_use]
pub fn len(&self) -> usize {
let inner = self.inner.lock();
inner.table.len()
}
/// Lock `tag`, blocking until it is available, and return a guard holding it.
/// Blocks on the per-tag mutex; the tag stays locked until the returned guard
/// (and all its clones) drop.
pub fn lock_tag(&self, tag: T) -> TagLockGuard<T> {
// Get or create a tag lock entry
let mutex = {
let mut inner = self.inner.lock();
// See if this tag is in the table
// and if not, add a new mutex for this tag
let entry = inner
.table
.entry(tag.clone())
.or_insert_with(|| TagLockTableEntry {
mutex: Arc::new(Mutex::new(())),
guards: 0,
});
// Increment the number of guards
entry.guards += 1;
// Return the mutex associated with the tag
entry.mutex.clone()
// Drop the table guard
};
// Lock the tag lock
let guard = mutex.lock_arc();
// Return the locked guard
TagLockGuard {
inner: Arc::new(TagLockGuardInner::new(self.clone(), tag, guard)),
}
}
/// Lock `tag` without blocking, returning `None` if it is already held.
/// On success the tag stays locked until the returned guard (and all its
/// clones) drop.
pub fn try_lock_tag(&self, tag: T) -> Option<TagLockGuard<T>> {
// Get or create a tag lock entry
let mut inner = self.inner.lock();
// See if this tag is in the table
// and if not, add a new mutex for this tag
let entry = inner.table.entry(tag.clone());
// Lock the tag lock
let guard = match entry {
std::collections::hash_map::Entry::Occupied(mut o) => {
let e = o.get_mut();
let guard = e.mutex.try_lock_arc()?;
e.guards += 1;
guard
}
std::collections::hash_map::Entry::Vacant(v) => {
let mutex = Arc::new(Mutex::new(()));
let guard = mutex.try_lock_arc().unwrap_or_log();
v.insert(TagLockTableEntry { mutex, guards: 1 });
guard
}
};
// Return guard
Some(TagLockGuard {
inner: Arc::new(TagLockGuardInner::new(self.clone(), tag, guard)),
})
}
}
impl<T> Default for TagLockTable<T>
where
T: Hash + Eq + Clone + Debug,
{
fn default() -> Self {
Self::new()
}
}