Debian Codegraph @

third_party/rust/regex-automata/src/util/pool.rs

raw
1 // This module provides a relatively simple thread-safe pool of reusable
2 // objects. For the most part, it's implemented by a stack represented by a
3 // Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat
4 // costly, in the case where a pool is accessed by the first thread that tried
5 // to get a value, we bypass the mutex. Here are some benchmarks showing the
6 // difference.
7 //
8 // 2022-10-15: These benchmarks are from the old regex crate and they aren't
9 // easy to reproduce because some rely on older implementations of Pool that
10 // are no longer around. I've left the results here for posterity, but any
11 // enterprising individual should feel encouraged to re-litigate the way Pool
12 // works. I am not at all certain it is the best approach.
13 //
14 // 1) misc::anchored_literal_long_non_match 21 (18571 MB/s)
15 // 2) misc::anchored_literal_long_non_match 107 (3644 MB/s)
16 // 3) misc::anchored_literal_long_non_match 45 (8666 MB/s)
17 // 4) misc::anchored_literal_long_non_match 19 (20526 MB/s)
18 //
19 // (1) represents our baseline: the master branch at the time of writing when
20 // using the 'thread_local' crate to implement the pool below.
21 //
22 // (2) represents a naive pool implemented completely via Mutex<Vec<T>>. There
23 // is no special trick for bypassing the mutex.
24 //
25 // (3) is the same as (2), except it uses Mutex<Vec<Box<T>>>. It is twice as
26 // fast because a Box<T> is much smaller than the T we use with a Pool in this
27 // crate. So pushing and popping a Box<T> from a Vec is quite a bit faster
28 // than for T.
29 //
30 // (4) is the same as (3), but with the trick for bypassing the mutex in the
31 // case of the first-to-get thread.
32 //
33 // Why move off of thread_local? Even though (4) is a hair faster than (1)
34 // above, this was not the main goal. The main goal was to move off of
35 // thread_local and find a way to *simply* re-capture some of its speed for
36 // regex's specific case. So again, why move off of it? The *primary* reason is
37 // because of memory leaks. See https://github.com/rust-lang/regex/issues/362
38 // for example. (Why do I want it to be simple? Well, I suppose what I mean is,
39 // "use as much safe code as possible to minimize risk and be as sure as I can
40 // be that it is correct.")
41 //
42 // My guess is that the thread_local design is probably not appropriate for
43 // regex since its memory usage scales to the number of active threads that
44 // have used a regex, where as the pool below scales to the number of threads
45 // that simultaneously use a regex. While neither case permits contraction,
46 // since we own the pool data structure below, we can add contraction if a
47 // clear use case pops up in the wild. More pressingly though, it seems that
48 // there are at least some use case patterns where one might have many threads
49 // sitting around that might have used a regex at one point. While thread_local
50 // does try to reuse space previously used by a thread that has since stopped,
51 // its maximal memory usage still scales with the total number of active
52 // threads. In contrast, the pool below scales with the total number of threads
53 // *simultaneously* using the pool. The hope is that this uses less memory
54 // overall. And if it doesn't, we can hopefully tune it somehow.
55 //
56 // It seems that these sort of conditions happen frequently
57 // in FFI inside of other more "managed" languages. This was
58 // mentioned in the issue linked above, and also mentioned here:
59 // https://github.com/BurntSushi/rure-go/issues/3. And in particular, users
60 // confirm that disabling the use of thread_local resolves the leak.
61 //
62 // There were other weaker reasons for moving off of thread_local as well.
63 // Namely, at the time, I was looking to reduce dependencies. And for something
64 // like regex, maintenance can be simpler when we own the full dependency tree.
65 //
66 // Note that I am not entirely happy with this pool. It has some subtle
67 // implementation details and is overall still observable (even with the
68 // thread owner optimization) in benchmarks. If someone wants to take a crack
69 // at building something better, please file an issue. Even if it means a
70 // different API. The API exposed by this pool is not the minimal thing that
71 // something like a 'Regex' actually needs. It could adapt to, for example,
72 // an API more like what is found in the 'thread_local' crate. However, we do
73 // really need to support the no-std alloc-only context, or else the regex
74 // crate wouldn't be able to support no-std alloc-only. However, I'm generally
75 // okay with making the alloc-only context slower (as it is here), although I
76 // do find it unfortunate.
77
78 /*!
79 A thread safe memory pool.
80
81 The principal type in this module is a [`Pool`]. It main use case is for
82 holding a thread safe collection of mutable scratch spaces (usually called
83 `Cache` in this crate) that regex engines need to execute a search. This then
84 permits sharing the same read-only regex object across multiple threads while
85 having a quick way of reusing scratch space in a thread safe way. This avoids
86 needing to re-create the scratch space for every search, which could wind up
87 being quite expensive.
88 */
89
90 /// A thread safe pool that works in an `alloc`-only context.
91 ///
92 /// Getting a value out comes with a guard. When that guard is dropped, the
93 /// value is automatically put back in the pool. The guard provides both a
94 /// `Deref` and a `DerefMut` implementation for easy access to an underlying
95 /// `T`.
96 ///
97 /// A `Pool` impls `Sync` when `T` is `Send` (even if `T` is not `Sync`). This
98 /// is possible because a pool is guaranteed to provide a value to exactly one
99 /// thread at any time.
100 ///
101 /// Currently, a pool never contracts in size. Its size is proportional to the
102 /// maximum number of simultaneous uses. This may change in the future.
103 ///
104 /// A `Pool` is a particularly useful data structure for this crate because
105 /// many of the regex engines require a mutable "cache" in order to execute
106 /// a search. Since regexes themselves tend to be global, the problem is then:
107 /// how do you get a mutable cache to execute a search? You could:
108 ///
109 /// 1. Use a `thread_local!`, which requires the standard library and requires
110 /// that the regex pattern be statically known.
111 /// 2. Use a `Pool`.
112 /// 3. Make the cache an explicit dependency in your code and pass it around.
113 /// 4. Put the cache state in a `Mutex`, but this means only one search can
114 /// execute at a time.
115 /// 5. Create a new cache for every search.
116 ///
117 /// A `thread_local!` is perhaps the best choice if it works for your use case.
118 /// Putting the cache in a mutex or creating a new cache for every search are
119 /// perhaps the worst choices. Of the remaining two choices, whether you use
120 /// this `Pool` or thread through a cache explicitly in your code is a matter
121 /// of taste and depends on your code architecture.
122 ///
123 /// # Warning: may use a spin lock
124 ///
125 /// When this crate is compiled _without_ the `std` feature, then this type
126 /// may used a spin lock internally. This can have subtle effects that may
127 /// be undesirable. See [Spinlocks Considered Harmful][spinharm] for a more
128 /// thorough treatment of this topic.
129 ///
130 /// [spinharm]: https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html
131 ///
132 /// # Example
133 ///
134 /// This example shows how to share a single hybrid regex among multiple
135 /// threads, while also safely getting exclusive access to a hybrid's
136 /// [`Cache`](crate::hybrid::regex::Cache) without preventing other searches
137 /// from running while your thread uses the `Cache`.
138 ///
139 /// ```
140 /// use regex_automata::{
141 /// hybrid::regex::{Cache, Regex},
142 /// util::{lazy::Lazy, pool::Pool},
143 /// Match,
144 /// };
145 ///
146 /// static RE: Lazy<Regex> =
147 /// Lazy::new(|| Regex::new("foo[0-9]+bar").unwrap());
148 /// static CACHE: Lazy<Pool<Cache>> =
149 /// Lazy::new(|| Pool::new(|| RE.create_cache()));
150 ///
151 /// let expected = Some(Match::must(0, 3..14));
152 /// assert_eq!(expected, RE.find(&mut CACHE.get(), b"zzzfoo12345barzzz"));
153 /// ```
154 pub struct Pool<T, F = fn() -> T>(alloc::boxed::Box<inner::Pool<T, F>>);
155
156 impl<T, F> Pool<T, F> {
157 /// Create a new pool. The given closure is used to create values in
158 /// the pool when necessary.
159 pub fn new(create: F) -> Pool<T, F> {
160 Pool(alloc::boxed::Box::new(inner::Pool::new(create)))
161 }
162 }
163
164 impl<T: Send, F: Fn() -> T> Pool<T, F> {
165 /// Get a value from the pool. The caller is guaranteed to have
166 /// exclusive access to the given value. Namely, it is guaranteed that
167 /// this will never return a value that was returned by another call to
168 /// `get` but was not put back into the pool.
169 ///
170 /// When the guard goes out of scope and its destructor is called, then
171 /// it will automatically be put back into the pool. Alternatively,
172 /// [`PoolGuard::put`] may be used to explicitly put it back in the pool
173 /// without relying on its destructor.
174 ///
175 /// Note that there is no guarantee provided about which value in the
176 /// pool is returned. That is, calling get, dropping the guard (causing
177 /// the value to go back into the pool) and then calling get again is
178 /// *not* guaranteed to return the same value received in the first `get`
179 /// call.
180 pub fn get(&self) -> PoolGuard<'_, T, F> {
181 PoolGuard(self.0.get())
182 }
183 }
184
185 impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
186 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
187 f.debug_tuple("Pool").field(&self.0).finish()
188 }
189 }
190
191 /// A guard that is returned when a caller requests a value from the pool.
192 ///
193 /// The purpose of the guard is to use RAII to automatically put the value
194 /// back in the pool once it's dropped.
195 pub struct PoolGuard<'a, T: Send, F: Fn() -> T>(inner::PoolGuard<'a, T, F>);
196
197 impl<'a, T: Send, F: Fn() -> T> PoolGuard<'a, T, F> {
198 /// Consumes this guard and puts it back into the pool.
199 ///
200 /// This circumvents the guard's `Drop` implementation. This can be useful
201 /// in circumstances where the automatic `Drop` results in poorer codegen,
202 /// such as calling non-inlined functions.
203 pub fn put(this: PoolGuard<'_, T, F>) {
204 inner::PoolGuard::put(this.0);
205 }
206 }
207
208 impl<'a, T: Send, F: Fn() -> T> core::ops::Deref for PoolGuard<'a, T, F> {
209 type Target = T;
210
211 fn deref(&self) -> &T {
212 self.0.value()
213 }
214 }
215
216 impl<'a, T: Send, F: Fn() -> T> core::ops::DerefMut for PoolGuard<'a, T, F> {
217 fn deref_mut(&mut self) -> &mut T {
218 self.0.value_mut()
219 }
220 }
221
222 impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
223 for PoolGuard<'a, T, F>
224 {
225 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
226 f.debug_tuple("PoolGuard").field(&self.0).finish()
227 }
228 }
229
230 #[cfg(feature = "std")]
231 mod inner {
232 use core::{
233 cell::UnsafeCell,
234 panic::{RefUnwindSafe, UnwindSafe},
235 sync::atomic::{AtomicUsize, Ordering},
236 };
237
238 use alloc::{boxed::Box, vec, vec::Vec};
239
240 use std::{sync::Mutex, thread_local};
241
242 /// An atomic counter used to allocate thread IDs.
243 ///
244 /// We specifically start our counter at 3 so that we can use the values
245 /// less than it as sentinels.
246 static COUNTER: AtomicUsize = AtomicUsize::new(3);
247
248 /// A thread ID indicating that there is no owner. This is the initial
249 /// state of a pool. Once a pool has an owner, there is no way to change
250 /// it.
251 static THREAD_ID_UNOWNED: usize = 0;
252
253 /// A thread ID indicating that the special owner value is in use and not
254 /// available. This state is useful for avoiding a case where the owner
255 /// of a pool calls `get` before putting the result of a previous `get`
256 /// call back into the pool.
257 static THREAD_ID_INUSE: usize = 1;
258
259 /// This sentinel is used to indicate that a guard has already been dropped
260 /// and should not be re-dropped. We use this because our drop code can be
261 /// called outside of Drop and thus there could be a bug in the internal
262 /// implementation that results in trying to put the same guard back into
263 /// the same pool multiple times, and *that* could result in UB if we
264 /// didn't mark the guard as already having been put back in the pool.
265 ///
266 /// So this isn't strictly necessary, but this let's us define some
267 /// routines as safe (like PoolGuard::put_imp) that we couldn't otherwise
268 /// do.
269 static THREAD_ID_DROPPED: usize = 2;
270
271 thread_local!(
272 /// A thread local used to assign an ID to a thread.
273 static THREAD_ID: usize = {
274 let next = COUNTER.fetch_add(1, Ordering::Relaxed);
275 // SAFETY: We cannot permit the reuse of thread IDs since reusing a
276 // thread ID might result in more than one thread "owning" a pool,
277 // and thus, permit accessing a mutable value from multiple threads
278 // simultaneously without synchronization. The intent of this panic
279 // is to be a sanity check. It is not expected that the thread ID
280 // space will actually be exhausted in practice. Even on a 32-bit
281 // system, it would require spawning 2^32 threads (although they
282 // wouldn't all need to run simultaneously, so it is in theory
283 // possible).
284 //
285 // This checks that the counter never wraps around, since atomic
286 // addition wraps around on overflow.
287 if next == 0 {
288 panic!("regex: thread ID allocation space exhausted");
289 }
290 next
291 };
292 );
293
294 /// A thread safe pool utilizing std-only features.
295 ///
296 /// The main difference between this and the simplistic alloc-only pool is
297 /// the use of std::sync::Mutex and an "owner thread" optimization that
298 /// makes accesses by the owner of a pool faster than all other threads.
299 /// This makes the common case of running a regex within a single thread
300 /// faster by avoiding mutex unlocking.
301 pub(super) struct Pool<T, F> {
302 /// A stack of T values to hand out. These are used when a Pool is
303 /// accessed by a thread that didn't create it.
304 stack: Mutex<Vec<Box<T>>>,
305 /// A function to create more T values when stack is empty and a caller
306 /// has requested a T.
307 create: F,
308 /// The ID of the thread that owns this pool. The owner is the thread
309 /// that makes the first call to 'get'. When the owner calls 'get', it
310 /// gets 'owner_val' directly instead of returning a T from 'stack'.
311 /// See comments elsewhere for details, but this is intended to be an
312 /// optimization for the common case that makes getting a T faster.
313 ///
314 /// It is initialized to a value of zero (an impossible thread ID) as a
315 /// sentinel to indicate that it is unowned.
316 owner: AtomicUsize,
317 /// A value to return when the caller is in the same thread that
318 /// first called `Pool::get`.
319 ///
320 /// This is set to None when a Pool is first created, and set to Some
321 /// once the first thread calls Pool::get.
322 owner_val: UnsafeCell<Option<T>>,
323 }
324
325 // SAFETY: Since we want to use a Pool from multiple threads simultaneously
326 // behind an Arc, we need for it to be Sync. In cases where T is sync,
327 // Pool<T> would be Sync. However, since we use a Pool to store mutable
328 // scratch space, we wind up using a T that has interior mutability and is
329 // thus itself not Sync. So what we *really* want is for our Pool<T> to by
330 // Sync even when T is not Sync (but is at least Send).
331 //
332 // The only non-sync aspect of a Pool is its 'owner_val' field, which is
333 // used to implement faster access to a pool value in the common case of
334 // a pool being accessed in the same thread in which it was created. The
335 // 'stack' field is also shared, but a Mutex<T> where T: Send is already
336 // Sync. So we only need to worry about 'owner_val'.
337 //
338 // The key is to guarantee that 'owner_val' can only ever be accessed from
339 // one thread. In our implementation below, we guarantee this by only
340 // returning the 'owner_val' when the ID of the current thread matches the
341 // ID of the thread that first called 'Pool::get'. Since this can only ever
342 // be one thread, it follows that only one thread can access 'owner_val' at
343 // any point in time. Thus, it is safe to declare that Pool<T> is Sync when
344 // T is Send.
345 //
346 // If there is a way to achieve our performance goals using safe code, then
347 // I would very much welcome a patch. As it stands, the implementation
348 // below tries to balance safety with performance. The case where a Regex
349 // is used from multiple threads simultaneously will suffer a bit since
350 // getting a value out of the pool will require unlocking a mutex.
351 //
352 // We require `F: Send + Sync` because we call `F` at any point on demand,
353 // potentially from multiple threads simultaneously.
354 unsafe impl<T: Send, F: Send + Sync> Sync for Pool<T, F> {}
355
356 // If T is UnwindSafe, then since we provide exclusive access to any
357 // particular value in the pool, it should therefore also be considered
358 // RefUnwindSafe. Also, since we use std::sync::Mutex, we get poisoning
359 // from it if another thread panics while the lock is held.
360 //
361 // We require `F: UnwindSafe + RefUnwindSafe` because we call `F` at any
362 // point on demand, so it needs to be unwind safe on both dimensions for
363 // the entire Pool to be unwind safe.
364 impl<T: UnwindSafe, F: UnwindSafe + RefUnwindSafe> RefUnwindSafe
365 for Pool<T, F>
366 {
367 }
368
369 impl<T, F> Pool<T, F> {
370 /// Create a new pool. The given closure is used to create values in
371 /// the pool when necessary.
372 pub(super) fn new(create: F) -> Pool<T, F> {
373 // MSRV(1.63): Mark this function as 'const'. I've arranged the
374 // code such that it should "just work." Then mark the public
375 // 'Pool::new' method as 'const' too. (The alloc-only Pool::new
376 // is already 'const', so that should "just work" too.) The only
377 // thing we're waiting for is Mutex::new to be const.
378 let owner = AtomicUsize::new(THREAD_ID_UNOWNED);
379 let owner_val = UnsafeCell::new(None); // init'd on first access
380 Pool { stack: Mutex::new(vec![]), create, owner, owner_val }
381 }
382 }
383
384 impl<T: Send, F: Fn() -> T> Pool<T, F> {
385 /// Get a value from the pool. This may block if another thread is also
386 /// attempting to retrieve a value from the pool.
387 pub(super) fn get(&self) -> PoolGuard<'_, T, F> {
388 // Our fast path checks if the caller is the thread that "owns"
389 // this pool. Or stated differently, whether it is the first thread
390 // that tried to extract a value from the pool. If it is, then we
391 // can return a T to the caller without going through a mutex.
392 //
393 // SAFETY: We must guarantee that only one thread gets access
394 // to this value. Since a thread is uniquely identified by the
395 // THREAD_ID thread local, it follows that if the caller's thread
396 // ID is equal to the owner, then only one thread may receive this
397 // value. This is also why we can get away with what looks like a
398 // racy load and a store. We know that if 'owner == caller', then
399 // only one thread can be here, so we don't need to worry about any
400 // other thread setting the owner to something else.
401 let caller = THREAD_ID.with(|id| *id);
402 let owner = self.owner.load(Ordering::Acquire);
403 if caller == owner {
404 self.owner.store(THREAD_ID_INUSE, Ordering::Release);
405 return self.guard_owned(caller);
406 }
407 self.get_slow(caller, owner)
408 }
409
410 /// This is the "slow" version that goes through a mutex to pop an
411 /// allocated value off a stack to return to the caller. (Or, if the
412 /// stack is empty, a new value is created.)
413 ///
414 /// If the pool has no owner, then this will set the owner.
415 #[cold]
416 fn get_slow(
417 &self,
418 caller: usize,
419 owner: usize,
420 ) -> PoolGuard<'_, T, F> {
421 if owner == THREAD_ID_UNOWNED {
422 // This sentinel means this pool is not yet owned. We try to
423 // atomically set the owner. If we do, then this thread becomes
424 // the owner and we can return a guard that represents the
425 // special T for the owner.
426 //
427 // Note that we set the owner to a different sentinel that
428 // indicates that the owned value is in use. The owner ID will
429 // get updated to the actual ID of this thread once the guard
430 // returned by this function is put back into the pool.
431 let res = self.owner.compare_exchange(
432 THREAD_ID_UNOWNED,
433 THREAD_ID_INUSE,
434 Ordering::AcqRel,
435 Ordering::Acquire,
436 );
437 if res.is_ok() {
438 // SAFETY: A successful CAS above implies this thread is
439 // the owner and that this is the only such thread that
440 // can reach here. Thus, there is no data race.
441 unsafe {
442 *self.owner_val.get() = Some((self.create)());
443 }
444 return self.guard_owned(caller);
445 }
446 }
447 let mut stack = self.stack.lock().unwrap();
448 let value = match stack.pop() {
449 None => Box::new((self.create)()),
450 Some(value) => value,
451 };
452 self.guard_stack(value)
453 }
454
455 /// Puts a value back into the pool. Callers don't need to call this.
456 /// Once the guard that's returned by 'get' is dropped, it is put back
457 /// into the pool automatically.
458 fn put_value(&self, value: Box<T>) {
459 let mut stack = self.stack.lock().unwrap();
460 stack.push(value);
461 }
462
463 /// Create a guard that represents the special owned T.
464 fn guard_owned(&self, caller: usize) -> PoolGuard<'_, T, F> {
465 PoolGuard { pool: self, value: Err(caller) }
466 }
467
468 /// Create a guard that contains a value from the pool's stack.
469 fn guard_stack(&self, value: Box<T>) -> PoolGuard<'_, T, F> {
470 PoolGuard { pool: self, value: Ok(value) }
471 }
472 }
473
474 impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
475 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
476 f.debug_struct("Pool")
477 .field("stack", &self.stack)
478 .field("owner", &self.owner)
479 .field("owner_val", &self.owner_val)
480 .finish()
481 }
482 }
483
484 /// A guard that is returned when a caller requests a value from the pool.
485 pub(super) struct PoolGuard<'a, T: Send, F: Fn() -> T> {
486 /// The pool that this guard is attached to.
487 pool: &'a Pool<T, F>,
488 /// This is Err when the guard represents the special "owned" value.
489 /// In which case, the value is retrieved from 'pool.owner_val'. And
490 /// in the special case of `Err(THREAD_ID_DROPPED)`, it means the
491 /// guard has been put back into the pool and should no longer be used.
492 value: Result<Box<T>, usize>,
493 }
494
495 impl<'a, T: Send, F: Fn() -> T> PoolGuard<'a, T, F> {
496 /// Return the underlying value.
497 pub(super) fn value(&self) -> &T {
498 match self.value {
499 Ok(ref v) => &**v,
500 // SAFETY: This is safe because the only way a PoolGuard gets
501 // created for self.value=Err is when the current thread
502 // corresponds to the owning thread, of which there can only
503 // be one. Thus, we are guaranteed to be providing exclusive
504 // access here which makes this safe.
505 //
506 // Also, since 'owner_val' is guaranteed to be initialized
507 // before an owned PoolGuard is created, the unchecked unwrap
508 // is safe.
509 Err(id) => unsafe {
510 // This assert is *not* necessary for safety, since we
511 // should never be here if the guard had been put back into
512 // the pool. This is a sanity check to make sure we didn't
513 // break an internal invariant.
514 debug_assert_ne!(THREAD_ID_DROPPED, id);
515 (*self.pool.owner_val.get()).as_ref().unwrap_unchecked()
516 },
517 }
518 }
519
520 /// Return the underlying value as a mutable borrow.
521 pub(super) fn value_mut(&mut self) -> &mut T {
522 match self.value {
523 Ok(ref mut v) => &mut **v,
524 // SAFETY: This is safe because the only way a PoolGuard gets
525 // created for self.value=None is when the current thread
526 // corresponds to the owning thread, of which there can only
527 // be one. Thus, we are guaranteed to be providing exclusive
528 // access here which makes this safe.
529 //
530 // Also, since 'owner_val' is guaranteed to be initialized
531 // before an owned PoolGuard is created, the unwrap_unchecked
532 // is safe.
533 Err(id) => unsafe {
534 // This assert is *not* necessary for safety, since we
535 // should never be here if the guard had been put back into
536 // the pool. This is a sanity check to make sure we didn't
537 // break an internal invariant.
538 debug_assert_ne!(THREAD_ID_DROPPED, id);
539 (*self.pool.owner_val.get()).as_mut().unwrap_unchecked()
540 },
541 }
542 }
543
544 /// Consumes this guard and puts it back into the pool.
545 pub(super) fn put(this: PoolGuard<'_, T, F>) {
546 // Since this is effectively consuming the guard and putting the
547 // value back into the pool, there's no reason to run its Drop
548 // impl after doing this. I don't believe there is a correctness
549 // problem with doing so, but there's definitely a perf problem
550 // by redoing this work. So we avoid it.
551 let mut this = core::mem::ManuallyDrop::new(this);
552 this.put_imp();
553 }
554
555 /// Puts this guard back into the pool by only borrowing the guard as
556 /// mutable. This should be called at most once.
557 #[inline(always)]
558 fn put_imp(&mut self) {
559 match core::mem::replace(&mut self.value, Err(THREAD_ID_DROPPED)) {
560 Ok(value) => self.pool.put_value(value),
561 // If this guard has a value "owned" by the thread, then
562 // the Pool guarantees that this is the ONLY such guard.
563 // Therefore, in order to place it back into the pool and make
564 // it available, we need to change the owner back to the owning
565 // thread's ID. But note that we use the ID that was stored in
566 // the guard, since a guard can be moved to another thread and
567 // dropped. (A previous iteration of this code read from the
568 // THREAD_ID thread local, which uses the ID of the current
569 // thread which may not be the ID of the owning thread! This
570 // also avoids the TLS access, which is likely a hair faster.)
571 Err(owner) => {
572 // If we hit this point, it implies 'put_imp' has been
573 // called multiple times for the same guard which in turn
574 // corresponds to a bug in this implementation.
575 assert_ne!(THREAD_ID_DROPPED, owner);
576 self.pool.owner.store(owner, Ordering::Release);
577 }
578 }
579 }
580 }
581
582 impl<'a, T: Send, F: Fn() -> T> Drop for PoolGuard<'a, T, F> {
583 fn drop(&mut self) {
584 self.put_imp();
585 }
586 }
587
588 impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
589 for PoolGuard<'a, T, F>
590 {
591 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
592 f.debug_struct("PoolGuard")
593 .field("pool", &self.pool)
594 .field("value", &self.value)
595 .finish()
596 }
597 }
598 }
599
600 // FUTURE: We should consider using Mara Bos's nearly-lock-free version of this
601 // here: https://gist.github.com/m-ou-se/5fdcbdf7dcf4585199ce2de697f367a4.
602 //
603 // One reason why I did things with a "mutex" below is that it isolates the
604 // safety concerns to just the Mutex, where as the safety of Mara's pool is a
605 // bit more sprawling. I also expect this code to not be used that much, and
606 // so is unlikely to get as much real world usage with which to test it. That
607 // means the "obviously correct" lever is an important one.
608 //
609 // The specific reason to use Mara's pool is that it is likely faster and also
610 // less likely to hit problems with spin-locks, although it is not completely
611 // impervious to them.
612 //
613 // The best solution to this problem, probably, is a truly lock free pool. That
614 // could be done with a lock free linked list. The issue is the ABA problem. It
615 // is difficult to avoid, and doing so is complex. BUT, the upshot of that is
616 // that if we had a truly lock free pool, then we could also use it above in
617 // the 'std' pool instead of a Mutex because it should be completely free the
618 // problems that come from spin-locks.
619 #[cfg(not(feature = "std"))]
620 mod inner {
621 use core::{
622 cell::UnsafeCell,
623 panic::{RefUnwindSafe, UnwindSafe},
624 sync::atomic::{AtomicBool, Ordering},
625 };
626
627 use alloc::{boxed::Box, vec, vec::Vec};
628
629 /// A thread safe pool utilizing alloc-only features.
630 ///
631 /// Unlike the std version, it doesn't seem possible(?) to implement the
632 /// "thread owner" optimization because alloc-only doesn't have any concept
633 /// of threads. So the best we can do is just a normal stack. This will
634 /// increase latency in alloc-only environments.
635 pub(super) struct Pool<T, F> {
636 /// A stack of T values to hand out. These are used when a Pool is
637 /// accessed by a thread that didn't create it.
638 stack: Mutex<Vec<Box<T>>>,
639 /// A function to create more T values when stack is empty and a caller
640 /// has requested a T.
641 create: F,
642 }
643
644 // If T is UnwindSafe, then since we provide exclusive access to any
645 // particular value in the pool, it should therefore also be considered
646 // RefUnwindSafe.
647 impl<T: UnwindSafe, F: UnwindSafe> RefUnwindSafe for Pool<T, F> {}
648
649 impl<T, F> Pool<T, F> {
650 /// Create a new pool. The given closure is used to create values in
651 /// the pool when necessary.
652 pub(super) const fn new(create: F) -> Pool<T, F> {
653 Pool { stack: Mutex::new(vec![]), create }
654 }
655 }
656
657 impl<T: Send, F: Fn() -> T> Pool<T, F> {
658 /// Get a value from the pool. This may block if another thread is also
659 /// attempting to retrieve a value from the pool.
660 pub(super) fn get(&self) -> PoolGuard<'_, T, F> {
661 let mut stack = self.stack.lock();
662 let value = match stack.pop() {
663 None => Box::new((self.create)()),
664 Some(value) => value,
665 };
666 PoolGuard { pool: self, value: Some(value) }
667 }
668
669 fn put(&self, guard: PoolGuard<'_, T, F>) {
670 let mut guard = core::mem::ManuallyDrop::new(guard);
671 if let Some(value) = guard.value.take() {
672 self.put_value(value);
673 }
674 }
675
676 /// Puts a value back into the pool. Callers don't need to call this.
677 /// Once the guard that's returned by 'get' is dropped, it is put back
678 /// into the pool automatically.
679 fn put_value(&self, value: Box<T>) {
680 let mut stack = self.stack.lock();
681 stack.push(value);
682 }
683 }
684
685 impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
686 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
687 f.debug_struct("Pool").field("stack", &self.stack).finish()
688 }
689 }
690
691 /// A guard that is returned when a caller requests a value from the pool.
692 pub(super) struct PoolGuard<'a, T: Send, F: Fn() -> T> {
693 /// The pool that this guard is attached to.
694 pool: &'a Pool<T, F>,
695 /// This is None after the guard has been put back into the pool.
696 value: Option<Box<T>>,
697 }
698
699 impl<'a, T: Send, F: Fn() -> T> PoolGuard<'a, T, F> {
700 /// Return the underlying value.
701 pub(super) fn value(&self) -> &T {
702 self.value.as_deref().unwrap()
703 }
704
705 /// Return the underlying value as a mutable borrow.
706 pub(super) fn value_mut(&mut self) -> &mut T {
707 self.value.as_deref_mut().unwrap()
708 }
709
710 /// Consumes this guard and puts it back into the pool.
711 pub(super) fn put(this: PoolGuard<'_, T, F>) {
712 // Since this is effectively consuming the guard and putting the
713 // value back into the pool, there's no reason to run its Drop
714 // impl after doing this. I don't believe there is a correctness
715 // problem with doing so, but there's definitely a perf problem
716 // by redoing this work. So we avoid it.
717 let mut this = core::mem::ManuallyDrop::new(this);
718 this.put_imp();
719 }
720
721 /// Puts this guard back into the pool by only borrowing the guard as
722 /// mutable. This should be called at most once.
723 #[inline(always)]
724 fn put_imp(&mut self) {
725 if let Some(value) = self.value.take() {
726 self.pool.put_value(value);
727 }
728 }
729 }
730
731 impl<'a, T: Send, F: Fn() -> T> Drop for PoolGuard<'a, T, F> {
732 fn drop(&mut self) {
733 self.put_imp();
734 }
735 }
736
737 impl<'a, T: Send + core::fmt::Debug, F: Fn() -> T> core::fmt::Debug
738 for PoolGuard<'a, T, F>
739 {
740 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
741 f.debug_struct("PoolGuard")
742 .field("pool", &self.pool)
743 .field("value", &self.value)
744 .finish()
745 }
746 }
747
748 /// A spin-lock based mutex. Yes, I have read spinlocks cosnidered
749 /// harmful[1], and if there's a reasonable alternative choice, I'll
750 /// happily take it.
751 ///
752 /// I suspect the most likely alternative here is a Treiber stack, but
753 /// implementing one correctly in a way that avoids the ABA problem looks
754 /// subtle enough that I'm not sure I want to attempt that. But otherwise,
755 /// we only need a mutex in order to implement our pool, so if there's
756 /// something simpler we can use that works for our `Pool` use case, then
757 /// that would be great.
758 ///
759 /// Note that this mutex does not do poisoning.
760 ///
761 /// [1]: https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html
762 #[derive(Debug)]
763 struct Mutex<T> {
764 locked: AtomicBool,
765 data: UnsafeCell<T>,
766 }
767
768 // SAFETY: Since a Mutex guarantees exclusive access, as long as we can
769 // send it across threads, it must also be Sync.
770 unsafe impl<T: Send> Sync for Mutex<T> {}
771
772 impl<T> Mutex<T> {
773 /// Create a new mutex for protecting access to the given value across
774 /// multiple threads simultaneously.
775 const fn new(value: T) -> Mutex<T> {
776 Mutex {
777 locked: AtomicBool::new(false),
778 data: UnsafeCell::new(value),
779 }
780 }
781
782 /// Lock this mutex and return a guard providing exclusive access to
783 /// `T`. This blocks if some other thread has already locked this
784 /// mutex.
785 fn lock(&self) -> MutexGuard<'_, T> {
786 while self
787 .locked
788 .compare_exchange(
789 false,
790 true,
791 Ordering::AcqRel,
792 Ordering::Acquire,
793 )
794 .is_err()
795 {
796 core::hint::spin_loop();
797 }
798 // SAFETY: The only way we're here is if we successfully set
799 // 'locked' to true, which implies we must be the only thread here
800 // and thus have exclusive access to 'data'.
801 let data = unsafe { &mut *self.data.get() };
802 MutexGuard { locked: &self.locked, data }
803 }
804 }
805
806 /// A guard that derefs to &T and &mut T. When it's dropped, the lock is
807 /// released.
808 #[derive(Debug)]
809 struct MutexGuard<'a, T> {
810 locked: &'a AtomicBool,
811 data: &'a mut T,
812 }
813
814 impl<'a, T> core::ops::Deref for MutexGuard<'a, T> {
815 type Target = T;
816
817 fn deref(&self) -> &T {
818 self.data
819 }
820 }
821
822 impl<'a, T> core::ops::DerefMut for MutexGuard<'a, T> {
823 fn deref_mut(&mut self) -> &mut T {
824 self.data
825 }
826 }
827
828 impl<'a, T> Drop for MutexGuard<'a, T> {
829 fn drop(&mut self) {
830 // Drop means 'data' is no longer accessible, so we can unlock
831 // the mutex.
832 self.locked.store(false, Ordering::Release);
833 }
834 }
835 }
836
837 #[cfg(test)]
838 mod tests {
839 use core::panic::{RefUnwindSafe, UnwindSafe};
840
841 use alloc::{boxed::Box, vec, vec::Vec};
842
843 use super::*;
844
845 #[test]
846 fn oibits() {
847 fn assert_oitbits<T: Send + Sync + UnwindSafe + RefUnwindSafe>() {}
848 assert_oitbits::<Pool<Vec<u32>>>();
849 assert_oitbits::<Pool<core::cell::RefCell<Vec<u32>>>>();
850 assert_oitbits::<
851 Pool<
852 Vec<u32>,
853 Box<
854 dyn Fn() -> Vec<u32>
855 + Send
856 + Sync
857 + UnwindSafe
858 + RefUnwindSafe,
859 >,
860 >,
861 >();
862 }
863
864 // Tests that Pool implements the "single owner" optimization. That is, the
865 // thread that first accesses the pool gets its own copy, while all other
866 // threads get distinct copies.
867 #[cfg(feature = "std")]
868 #[test]
869 fn thread_owner_optimization() {
870 use std::{cell::RefCell, sync::Arc, vec};
871
872 let pool: Arc<Pool<RefCell<Vec<char>>>> =
873 Arc::new(Pool::new(|| RefCell::new(vec!['a'])));
874 pool.get().borrow_mut().push('x');
875
876 let pool1 = pool.clone();
877 let t1 = std::thread::spawn(move || {
878 let guard = pool1.get();
879 guard.borrow_mut().push('y');
880 });
881
882 let pool2 = pool.clone();
883 let t2 = std::thread::spawn(move || {
884 let guard = pool2.get();
885 guard.borrow_mut().push('z');
886 });
887
888 t1.join().unwrap();
889 t2.join().unwrap();
890
891 // If we didn't implement the single owner optimization, then one of
892 // the threads above is likely to have mutated the [a, x] vec that
893 // we stuffed in the pool before spawning the threads. But since
894 // neither thread was first to access the pool, and because of the
895 // optimization, we should be guaranteed that neither thread mutates
896 // the special owned pool value.
897 //
898 // (Technically this is an implementation detail and not a contract of
899 // Pool's API.)
900 assert_eq!(vec!['a', 'x'], *pool.get().borrow());
901 }
902
903 // This tests that if the "owner" of a pool asks for two values, then it
904 // gets two distinct values and not the same one. This test failed in the
905 // course of developing the pool, which in turn resulted in UB because it
906 // permitted getting aliasing &mut borrows to the same place in memory.
907 #[test]
908 fn thread_owner_distinct() {
909 let pool = Pool::new(|| vec!['a']);
910
911 {
912 let mut g1 = pool.get();
913 let v1 = &mut *g1;
914 let mut g2 = pool.get();
915 let v2 = &mut *g2;
916 v1.push('b');
917 v2.push('c');
918 assert_eq!(&mut vec!['a', 'b'], v1);
919 assert_eq!(&mut vec!['a', 'c'], v2);
920 }
921 // This isn't technically guaranteed, but we
922 // expect to now get the "owned" value (the first
923 // call to 'get()' above) now that it's back in
924 // the pool.
925 assert_eq!(&mut vec!['a', 'b'], &mut *pool.get());
926 }
927
928 // This tests that we can share a guard with another thread, mutate the
929 // underlying value and everything works. This failed in the course of
930 // developing a pool since the pool permitted 'get()' to return the same
931 // value to the owner thread, even before the previous value was put back
932 // into the pool. This in turn resulted in this test producing a data race.
933 #[cfg(feature = "std")]
934 #[test]
935 fn thread_owner_sync() {
936 let pool = Pool::new(|| vec!['a']);
937 {
938 let mut g1 = pool.get();
939 let mut g2 = pool.get();
940 std::thread::scope(|s| {
941 s.spawn(|| {
942 g1.push('b');
943 });
944 s.spawn(|| {
945 g2.push('c');
946 });
947 });
948
949 let v1 = &mut *g1;
950 let v2 = &mut *g2;
951 assert_eq!(&mut vec!['a', 'b'], v1);
952 assert_eq!(&mut vec!['a', 'c'], v2);
953 }
954
955 // This isn't technically guaranteed, but we
956 // expect to now get the "owned" value (the first
957 // call to 'get()' above) now that it's back in
958 // the pool.
959 assert_eq!(&mut vec!['a', 'b'], &mut *pool.get());
960 }
961
962 // This tests that if we move a PoolGuard that is owned by the current
963 // thread to another thread and drop it, then the thread owner doesn't
964 // change. During development of the pool, this test failed because the
965 // PoolGuard assumed it was dropped in the same thread from which it was
966 // created, and thus used the current thread's ID as the owner, which could
967 // be different than the actual owner of the pool.
968 #[cfg(feature = "std")]
969 #[test]
970 fn thread_owner_send_drop() {
971 let pool = Pool::new(|| vec!['a']);
972 // Establishes this thread as the owner.
973 {
974 pool.get().push('b');
975 }
976 std::thread::scope(|s| {
977 // Sanity check that we get the same value back.
978 // (Not technically guaranteed.)
979 let mut g = pool.get();
980 assert_eq!(&vec!['a', 'b'], &*g);
981 // Now push it to another thread and drop it.
982 s.spawn(move || {
983 g.push('c');
984 })
985 .join()
986 .unwrap();
987 });
988 // Now check that we're still the owner. This is not technically
989 // guaranteed by the API, but is true in practice given the thread
990 // owner optimization.
991 assert_eq!(&vec!['a', 'b', 'c'], &*pool.get());
992 }
993 }