regex_pool/util/pool.rs
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/*!
79A thread safe memory pool.
80
81The principal type in this module is a [`Pool`]. It main use case is for
82holding 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
84permits sharing the same read-only regex object across multiple threads while
85having a quick way of reusing scratch space in a thread safe way. This avoids
86needing to re-create the scratch space for every search, which could wind up
87being 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 pool among callers while safely getting
135/// exclusive access to a reusable value.
136///
137/// ```
138/// use regex_pool::util::pool::{Pool, PoolGuard};
139///
140/// let pool = Pool::<_, _, 8>::new(|| Vec::<u8>::new());
141/// let mut scratch = pool.get();
142/// scratch.extend_from_slice(b"cached allocation");
143/// assert_eq!(b"cached allocation", &scratch[..]);
144/// PoolGuard::put(scratch);
145/// ```
146pub struct Pool<T, F = fn() -> T, const MAX_POOL_STACKS: usize = 8>(
147 alloc::boxed::Box<inner::Pool<T, F, MAX_POOL_STACKS>>,
148);
149
150impl<T, F, const MAX_POOL_STACKS: usize> Pool<T, F, MAX_POOL_STACKS> {
151 /// Create a new pool, inferring types based on the closure provided.
152 pub fn new(create: F) -> Pool<T, F, MAX_POOL_STACKS> {
153 Pool(alloc::boxed::Box::new(
154 inner::Pool::<T, F, MAX_POOL_STACKS>::new(create),
155 ))
156 }
157}
158
159impl<T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
160 Pool<T, F, MAX_POOL_STACKS>
161{
162 /// Get a value from the pool. The caller is guaranteed to have
163 /// exclusive access to the given value. Namely, it is guaranteed that
164 /// this will never return a value that was returned by another call to
165 /// `get` but was not put back into the pool.
166 ///
167 /// When the guard goes out of scope and its destructor is called, then
168 /// it will automatically be put back into the pool. Alternatively,
169 /// [`PoolGuard::put`] may be used to explicitly put it back in the pool
170 /// without relying on its destructor.
171 ///
172 /// Note that there is no guarantee provided about which value in the
173 /// pool is returned. That is, calling get, dropping the guard (causing
174 /// the value to go back into the pool) and then calling get again is
175 /// *not* guaranteed to return the same value received in the first `get`
176 /// call.
177 #[inline]
178 pub fn get(&self) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
179 PoolGuard(self.0.get())
180 }
181}
182
183impl<T: core::fmt::Debug, F> core::fmt::Debug for Pool<T, F> {
184 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
185 f.debug_tuple("Pool").field(&self.0).finish()
186 }
187}
188
189/// A guard that is returned when a caller requests a value from the pool.
190///
191/// The purpose of the guard is to use RAII to automatically put the value
192/// back in the pool once it's dropped.
193pub struct PoolGuard<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>(
194 inner::PoolGuard<'a, T, F, MAX_POOL_STACKS>,
195);
196
197impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
198 PoolGuard<'a, T, F, MAX_POOL_STACKS>
199{
200 /// Consumes this guard and puts it back into the pool.
201 ///
202 /// This circumvents the guard's `Drop` implementation. This can be useful
203 /// in circumstances where the automatic `Drop` results in poorer codegen,
204 /// such as calling non-inlined functions.
205 #[inline]
206 pub fn put(this: PoolGuard<'_, T, F, MAX_POOL_STACKS>) {
207 inner::PoolGuard::put(this.0);
208 }
209}
210
211impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize> core::ops::Deref
212 for PoolGuard<'a, T, F, MAX_POOL_STACKS>
213{
214 type Target = T;
215
216 #[inline]
217 fn deref(&self) -> &T {
218 self.0.value()
219 }
220}
221
222impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
223 core::ops::DerefMut for PoolGuard<'a, T, F, MAX_POOL_STACKS>
224{
225 #[inline]
226 fn deref_mut(&mut self) -> &mut T {
227 self.0.value_mut()
228 }
229}
230
231impl<
232 'a,
233 T: Send + core::fmt::Debug,
234 F: Fn() -> T,
235 const MAX_POOL_STACKS: usize,
236 > core::fmt::Debug for PoolGuard<'a, T, F, MAX_POOL_STACKS>
237{
238 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
239 f.debug_tuple("PoolGuard").field(&self.0).finish()
240 }
241}
242
243#[cfg(feature = "std")]
244mod inner {
245 use core::{
246 cell::UnsafeCell,
247 panic::{RefUnwindSafe, UnwindSafe},
248 sync::atomic::{AtomicUsize, Ordering},
249 };
250
251 use alloc::{boxed::Box, vec, vec::Vec};
252
253 use std::{sync::Mutex, thread_local};
254
255 /// An atomic counter used to allocate thread IDs.
256 ///
257 /// We specifically start our counter at 3 so that we can use the values
258 /// less than it as sentinels.
259 static COUNTER: AtomicUsize = AtomicUsize::new(3);
260
261 /// A thread ID indicating that there is no owner. This is the initial
262 /// state of a pool. Once a pool has an owner, there is no way to change
263 /// it.
264 static THREAD_ID_UNOWNED: usize = 0;
265
266 /// A thread ID indicating that the special owner value is in use and not
267 /// available. This state is useful for avoiding a case where the owner
268 /// of a pool calls `get` before putting the result of a previous `get`
269 /// call back into the pool.
270 static THREAD_ID_INUSE: usize = 1;
271
272 /// This sentinel is used to indicate that a guard has already been dropped
273 /// and should not be re-dropped. We use this because our drop code can be
274 /// called outside of Drop and thus there could be a bug in the internal
275 /// implementation that results in trying to put the same guard back into
276 /// the same pool multiple times, and *that* could result in UB if we
277 /// didn't mark the guard as already having been put back in the pool.
278 ///
279 /// So this isn't strictly necessary, but this let's us define some
280 /// routines as safe (like PoolGuard::put_imp) that we couldn't otherwise
281 /// do.
282 static THREAD_ID_DROPPED: usize = 2;
283
284 // The number of stacks we use inside of the pool. These are only used for
285 // non-owners. That is, these represent the "slow" path.
286 //
287 // In the original implementation of this pool, we only used a single
288 // stack. While this might be okay for a couple threads, the prevalence of
289 // 32, 64 and even 128 core CPUs has made it untenable. The contention
290 // such an environment introduces when threads are doing a lot of searches
291 // on short haystacks (a not uncommon use case) is palpable and leads to
292 // huge slowdowns.
293 //
294 // This constant reflects a change from using one stack to the number of
295 // stacks that this constant is set to. The stack for a particular thread
296 // is simply chosen by `thread_id % MAX_POOL_STACKS`. The idea behind
297 // this setup is that there should be a good chance that accesses to the
298 // pool will be distributed over several stacks instead of all of them
299 // converging to one.
300 //
301 // This is not a particularly smart or dynamic strategy. Fixing this to a
302 // specific number has at least two downsides. First is that it will help,
303 // say, an 8 core CPU more than it will a 128 core CPU. (But, crucially,
304 // it will still help the 128 core case.) Second is that this may wind
305 // up being a little wasteful with respect to memory usage. Namely, if a
306 // regex is used on one thread and then moved to another thread, then it
307 // could result in creating a new copy of the data in the pool even though
308 // only one is actually needed.
309 //
310 // And that memory usage bit is why this is set to 8 and not, say, 64.
311 // Keeping it at 8 limits, to an extent, how much unnecessary memory can
312 // be allocated.
313 //
314 // In an ideal world, we'd be able to have something like this:
315 //
316 // * Grow the number of stacks as the number of concurrent callers
317 // increases. I spent a little time trying this, but even just adding an
318 // atomic addition/subtraction for each pop/push for tracking concurrent
319 // callers led to a big perf hit. Since even more work would seemingly be
320 // required than just an addition/subtraction, I abandoned this approach.
321 // * The maximum amount of memory used should scale with respect to the
322 // number of concurrent callers and *not* the total number of existing
323 // threads. This is primarily why the `thread_local` crate isn't used, as
324 // as some environments spin up a lot of threads. This led to multiple
325 // reports of extremely high memory usage (often described as memory
326 // leaks).
327 // * Even more ideally, the pool should contract in size. That is, it
328 // should grow with bursts and then shrink. But this is a pretty thorny
329 // issue to tackle and it might be better to just not.
330 // * It would be nice to explore the use of, say, a lock-free stack
331 // instead of using a mutex to guard a `Vec` that is ultimately just
332 // treated as a stack. The main thing preventing me from exploring this
333 // is the ABA problem. The `crossbeam` crate has tools for dealing with
334 // this sort of problem (via its epoch based memory reclamation strategy),
335 // but I can't justify bringing in all of `crossbeam` as a dependency of
336 // `regex` for this.
337 //
338 // See this issue for more context and discussion:
339 // https://github.com/rust-lang/regex/issues/934
340 // const MAX_POOL_STACKS: usize = 32;
341
342 thread_local!(
343 /// A thread local used to assign an ID to a thread.
344 static THREAD_ID: usize = {
345 let next = COUNTER.fetch_add(1, Ordering::Relaxed);
346 // SAFETY: We cannot permit the reuse of thread IDs since reusing a
347 // thread ID might result in more than one thread "owning" a pool,
348 // and thus, permit accessing a mutable value from multiple threads
349 // simultaneously without synchronization. The intent of this panic
350 // is to be a sanity check. It is not expected that the thread ID
351 // space will actually be exhausted in practice. Even on a 32-bit
352 // system, it would require spawning 2^32 threads (although they
353 // wouldn't all need to run simultaneously, so it is in theory
354 // possible).
355 //
356 // This checks that the counter never wraps around, since atomic
357 // addition wraps around on overflow.
358 if next == 0 {
359 panic!("regex: thread ID allocation space exhausted");
360 }
361 next
362 };
363 );
364
365 /// This puts each stack in the pool below into its own cache line. This is
366 /// an absolutely critical optimization that tends to have the most impact
367 /// in high contention workloads. Without forcing each mutex protected
368 /// into its own cache line, high contention exacerbates the performance
369 /// problem by causing "false sharing." By putting each mutex in its own
370 /// cache-line, we avoid the false sharing problem and the affects of
371 /// contention are greatly reduced.
372 #[derive(Debug)]
373 #[repr(C, align(64))]
374 struct CacheLine<T>(T);
375
376 /// A thread safe pool utilizing std-only features.
377 ///
378 /// The main difference between this and the simplistic alloc-only pool is
379 /// the use of std::sync::Mutex and an "owner thread" optimization that
380 /// makes accesses by the owner of a pool faster than all other threads.
381 /// This makes the common case of running a regex within a single thread
382 /// faster by avoiding mutex unlocking.
383 pub(super) struct Pool<T, F, const MAX_POOL_STACKS: usize> {
384 /// A function to create more T values when stack is empty and a caller
385 /// has requested a T.
386 create: F,
387 /// Multiple stacks of T values to hand out. These are used when a Pool
388 /// is accessed by a thread that didn't create it.
389 ///
390 /// Conceptually this is `Mutex<Vec<Box<T>>>`, but sharded out to make
391 /// it scale better under high contention work-loads. We index into
392 /// this sequence via `thread_id % stacks.len()`.
393 stacks: Vec<CacheLine<Mutex<Vec<Box<T>>>>>,
394 /// The ID of the thread that owns this pool. The owner is the thread
395 /// that makes the first call to 'get'. When the owner calls 'get', it
396 /// gets 'owner_val' directly instead of returning a T from 'stack'.
397 /// See comments elsewhere for details, but this is intended to be an
398 /// optimization for the common case that makes getting a T faster.
399 ///
400 /// It is initialized to a value of zero (an impossible thread ID) as a
401 /// sentinel to indicate that it is unowned.
402 owner: AtomicUsize,
403 /// A value to return when the caller is in the same thread that
404 /// first called `Pool::get`.
405 ///
406 /// This is set to None when a Pool is first created, and set to Some
407 /// once the first thread calls Pool::get.
408 owner_val: UnsafeCell<Option<T>>,
409 }
410
411 // SAFETY: Since we want to use a Pool from multiple threads simultaneously
412 // behind an Arc, we need for it to be Sync. In cases where T is sync,
413 // Pool<T> would be Sync. However, since we use a Pool to store mutable
414 // scratch space, we wind up using a T that has interior mutability and is
415 // thus itself not Sync. So what we *really* want is for our Pool<T> to by
416 // Sync even when T is not Sync (but is at least Send).
417 //
418 // The only non-sync aspect of a Pool is its 'owner_val' field, which is
419 // used to implement faster access to a pool value in the common case of
420 // a pool being accessed in the same thread in which it was created. The
421 // 'stack' field is also shared, but a Mutex<T> where T: Send is already
422 // Sync. So we only need to worry about 'owner_val'.
423 //
424 // The key is to guarantee that 'owner_val' can only ever be accessed from
425 // one thread. In our implementation below, we guarantee this by only
426 // returning the 'owner_val' when the ID of the current thread matches the
427 // ID of the thread that first called 'Pool::get'. Since this can only ever
428 // be one thread, it follows that only one thread can access 'owner_val' at
429 // any point in time. Thus, it is safe to declare that Pool<T> is Sync when
430 // T is Send.
431 //
432 // If there is a way to achieve our performance goals using safe code, then
433 // I would very much welcome a patch. As it stands, the implementation
434 // below tries to balance safety with performance. The case where a Regex
435 // is used from multiple threads simultaneously will suffer a bit since
436 // getting a value out of the pool will require unlocking a mutex.
437 //
438 // We require `F: Send + Sync` because we call `F` at any point on demand,
439 // potentially from multiple threads simultaneously.
440 unsafe impl<T: Send, F: Send + Sync, const MAX_POOL_STACKS: usize> Sync
441 for Pool<T, F, MAX_POOL_STACKS>
442 {
443 }
444
445 // If T is UnwindSafe, then since we provide exclusive access to any
446 // particular value in the pool, the pool should therefore also be
447 // considered UnwindSafe.
448 //
449 // We require `F: UnwindSafe + RefUnwindSafe` because we call `F` at any
450 // point on demand, so it needs to be unwind safe on both dimensions for
451 // the entire Pool to be unwind safe.
452 impl<
453 T: UnwindSafe,
454 F: UnwindSafe + RefUnwindSafe,
455 const MAX_POOL_STACKS: usize,
456 > UnwindSafe for Pool<T, F, MAX_POOL_STACKS>
457 {
458 }
459
460 // If T is UnwindSafe, then since we provide exclusive access to any
461 // particular value in the pool, the pool should therefore also be
462 // considered RefUnwindSafe.
463 //
464 // We require `F: UnwindSafe + RefUnwindSafe` because we call `F` at any
465 // point on demand, so it needs to be unwind safe on both dimensions for
466 // the entire Pool to be unwind safe.
467 impl<
468 T: UnwindSafe,
469 F: UnwindSafe + RefUnwindSafe,
470 const MAX_POOL_STACKS: usize,
471 > RefUnwindSafe for Pool<T, F, MAX_POOL_STACKS>
472 {
473 }
474
475 impl<T, F, const MAX_POOL_STACKS: usize> Pool<T, F, MAX_POOL_STACKS> {
476 /// Create a new pool. The given closure is used to create values in
477 /// the pool when necessary.
478 pub(super) fn new(create: F) -> Pool<T, F, MAX_POOL_STACKS> {
479 // FIXME: Now that we require 1.65+, Mutex::new is available as
480 // const... So we can almost mark this function as const. But of
481 // course, we're creating a Vec of stacks below (we didn't when I
482 // originally wrote this code). It seems like the best way to work
483 // around this would be to use a `[Stack; MAX_POOL_STACKS]` instead
484 // of a `Vec<Stack>`. I refrained from making this change at time
485 // of writing (2023/10/08) because I was making a lot of other
486 // changes at the same time and wanted to do this more carefully.
487 // Namely, because of the cache line optimization, that `[Stack;
488 // MAX_POOL_STACKS]` would be quite big. It's unclear how bad (if
489 // at all) that would be.
490 //
491 // Another choice would be to lazily allocate the stacks, but...
492 // I'm not so sure about that. Seems like a fair bit of complexity?
493 //
494 // Maybe there's a simple solution I'm missing.
495 //
496 // ... OK, I tried to fix this. First, I did it by putting `stacks`
497 // in an `UnsafeCell` and using a `Once` to lazily initialize it.
498 // I benchmarked it and everything looked okay. I then made this
499 // function `const` and thought I was just about done. But the
500 // public pool type wraps its inner pool in a `Box` to keep its
501 // size down. Blech.
502 //
503 // So then I thought that I could push the box down into this
504 // type (and leave the non-std version unboxed) and use the same
505 // `UnsafeCell` technique to lazily initialize it. This has the
506 // downside of the `Once` now needing to get hit in the owner fast
507 // path, but maybe that's OK? However, I then realized that we can
508 // only lazily initialize `stacks`, `owner` and `owner_val`. The
509 // `create` function needs to be put somewhere outside of the box.
510 // So now the pool is a `Box`, `Once` and a function. Now we're
511 // starting to defeat the point of boxing in the first place. So I
512 // backed out that change too.
513 //
514 // Back to square one. I maybe we just don't make a pool's
515 // constructor const and live with it. It's probably not a huge
516 // deal.
517 let mut stacks = Vec::with_capacity(MAX_POOL_STACKS);
518 for _ in 0..stacks.capacity() {
519 stacks.push(CacheLine(Mutex::new(vec![])));
520 }
521 let owner = AtomicUsize::new(THREAD_ID_UNOWNED);
522 let owner_val = UnsafeCell::new(None); // init'd on first access
523 Pool { create, stacks, owner, owner_val }
524 }
525 }
526
527 impl<T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
528 Pool<T, F, MAX_POOL_STACKS>
529 {
530 /// Get a value from the pool. This may block if another thread is also
531 /// attempting to retrieve a value from the pool.
532 #[inline]
533 pub(super) fn get(&self) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
534 // Our fast path checks if the caller is the thread that "owns"
535 // this pool. Or stated differently, whether it is the first thread
536 // that tried to extract a value from the pool. If it is, then we
537 // can return a T to the caller without going through a mutex.
538 //
539 // SAFETY: We must guarantee that only one thread gets access
540 // to this value. Since a thread is uniquely identified by the
541 // THREAD_ID thread local, it follows that if the caller's thread
542 // ID is equal to the owner, then only one thread may receive this
543 // value. This is also why we can get away with what looks like a
544 // racy load and a store. We know that if 'owner == caller', then
545 // only one thread can be here, so we don't need to worry about any
546 // other thread setting the owner to something else.
547 let caller = THREAD_ID.with(|id| *id);
548 let owner = self.owner.load(Ordering::Acquire);
549 if caller == owner {
550 // N.B. We could also do a CAS here instead of a load/store,
551 // but ad hoc benchmarking suggests it is slower. And a lot
552 // slower in the case where `get_slow` is common.
553 self.owner.store(THREAD_ID_INUSE, Ordering::Release);
554 return self.guard_owned(caller);
555 }
556 self.get_slow(caller, owner)
557 }
558
559 /// This is the "slow" version that goes through a mutex to pop an
560 /// allocated value off a stack to return to the caller. (Or, if the
561 /// stack is empty, a new value is created.)
562 ///
563 /// If the pool has no owner, then this will set the owner.
564 #[cold]
565 fn get_slow(
566 &self,
567 caller: usize,
568 owner: usize,
569 ) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
570 if owner == THREAD_ID_UNOWNED {
571 // This sentinel means this pool is not yet owned. We try to
572 // atomically set the owner. If we do, then this thread becomes
573 // the owner and we can return a guard that represents the
574 // special T for the owner.
575 //
576 // Note that we set the owner to a different sentinel that
577 // indicates that the owned value is in use. The owner ID will
578 // get updated to the actual ID of this thread once the guard
579 // returned by this function is put back into the pool.
580 let res = self.owner.compare_exchange(
581 THREAD_ID_UNOWNED,
582 THREAD_ID_INUSE,
583 Ordering::AcqRel,
584 Ordering::Acquire,
585 );
586 if res.is_ok() {
587 // SAFETY: A successful CAS above implies this thread is
588 // the owner and that this is the only such thread that
589 // can reach here. Thus, there is no data race.
590 unsafe {
591 *self.owner_val.get() = Some((self.create)());
592 }
593 return self.guard_owned(caller);
594 }
595 }
596 let stack_id = caller % self.stacks.len();
597 // We try to acquire exclusive access to this thread's stack, and
598 // if so, grab a value from it if we can. We put this in a loop so
599 // that it's easy to tweak and experiment with a different number
600 // of tries. In the end, I couldn't see anything obviously better
601 // than one attempt in ad hoc testing.
602 for _ in 0..1 {
603 let mut stack = match self.stacks[stack_id].0.try_lock() {
604 Err(_) => continue,
605 Ok(stack) => stack,
606 };
607 if let Some(value) = stack.pop() {
608 return self.guard_stack(value);
609 }
610 // Unlock the mutex guarding the stack before creating a fresh
611 // value since we no longer need the stack.
612 drop(stack);
613 let value = Box::new((self.create)());
614 return self.guard_stack(value);
615 }
616 // We're only here if we could get access to our stack, so just
617 // create a new value. This seems like it could be wasteful, but
618 // waiting for exclusive access to a stack when there's high
619 // contention is brutal for perf.
620 self.guard_stack_transient(Box::new((self.create)()))
621 }
622
623 /// Puts a value back into the pool. Callers don't need to call this.
624 /// Once the guard that's returned by 'get' is dropped, it is put back
625 /// into the pool automatically.
626 #[inline]
627 fn put_value(&self, value: Box<T>) {
628 let caller = THREAD_ID.with(|id| *id);
629 let stack_id = caller % self.stacks.len();
630 // As with trying to pop a value from this thread's stack, we
631 // merely attempt to get access to push this value back on the
632 // stack. If there's too much contention, we just give up and throw
633 // the value away.
634 //
635 // Interestingly, in ad hoc benchmarking, it is beneficial to
636 // attempt to push the value back more than once, unlike when
637 // popping the value. I don't have a good theory for why this is.
638 // I guess if we drop too many values then that winds up forcing
639 // the pop operation to create new fresh values and thus leads to
640 // less reuse. There's definitely a balancing act here.
641 for _ in 0..10 {
642 let mut stack = match self.stacks[stack_id].0.try_lock() {
643 Err(_) => continue,
644 Ok(stack) => stack,
645 };
646 stack.push(value);
647 return;
648 }
649 }
650
651 /// Create a guard that represents the special owned T.
652 #[inline]
653 fn guard_owned(
654 &self,
655 caller: usize,
656 ) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
657 PoolGuard { pool: self, value: Err(caller), discard: false }
658 }
659
660 /// Create a guard that contains a value from the pool's stack.
661 #[inline]
662 fn guard_stack(
663 &self,
664 value: Box<T>,
665 ) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
666 PoolGuard { pool: self, value: Ok(value), discard: false }
667 }
668
669 /// Create a guard that contains a value from the pool's stack with an
670 /// instruction to throw away the value instead of putting it back
671 /// into the pool.
672 #[inline]
673 fn guard_stack_transient(
674 &self,
675 value: Box<T>,
676 ) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
677 PoolGuard { pool: self, value: Ok(value), discard: true }
678 }
679 }
680
681 impl<T: core::fmt::Debug, F, const MAX_POOL_STACKS: usize> core::fmt::Debug
682 for Pool<T, F, MAX_POOL_STACKS>
683 {
684 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
685 f.debug_struct("Pool")
686 .field("stacks", &self.stacks)
687 .field("owner", &self.owner)
688 .field("owner_val", &self.owner_val)
689 .finish()
690 }
691 }
692
693 /// A guard that is returned when a caller requests a value from the pool.
694 pub(super) struct PoolGuard<
695 'a,
696 T: Send,
697 F: Fn() -> T,
698 const MAX_POOL_STACKS: usize,
699 > {
700 /// The pool that this guard is attached to.
701 pool: &'a Pool<T, F, MAX_POOL_STACKS>,
702 /// This is Err when the guard represents the special "owned" value.
703 /// In which case, the value is retrieved from 'pool.owner_val'. And
704 /// in the special case of `Err(THREAD_ID_DROPPED)`, it means the
705 /// guard has been put back into the pool and should no longer be used.
706 value: Result<Box<T>, usize>,
707 /// When true, the value should be discarded instead of being pushed
708 /// back into the pool. We tend to use this under high contention, and
709 /// this allows us to avoid inflating the size of the pool. (Because
710 /// under contention, we tend to create more values instead of waiting
711 /// for access to a stack of existing values.)
712 discard: bool,
713 }
714
715 impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
716 PoolGuard<'a, T, F, MAX_POOL_STACKS>
717 {
718 /// Return the underlying value.
719 #[inline]
720 pub(super) fn value(&self) -> &T {
721 match self.value {
722 Ok(ref v) => &**v,
723 // SAFETY: This is safe because the only way a PoolGuard gets
724 // created for self.value=Err is when the current thread
725 // corresponds to the owning thread, of which there can only
726 // be one. Thus, we are guaranteed to be providing exclusive
727 // access here which makes this safe.
728 //
729 // Also, since 'owner_val' is guaranteed to be initialized
730 // before an owned PoolGuard is created, the unchecked unwrap
731 // is safe.
732 Err(id) => unsafe {
733 // This assert is *not* necessary for safety, since we
734 // should never be here if the guard had been put back into
735 // the pool. This is a sanity check to make sure we didn't
736 // break an internal invariant.
737 debug_assert_ne!(THREAD_ID_DROPPED, id);
738 (*self.pool.owner_val.get()).as_ref().unwrap_unchecked()
739 },
740 }
741 }
742
743 /// Return the underlying value as a mutable borrow.
744 #[inline]
745 pub(super) fn value_mut(&mut self) -> &mut T {
746 match self.value {
747 Ok(ref mut v) => &mut **v,
748 // SAFETY: This is safe because the only way a PoolGuard gets
749 // created for self.value=None is when the current thread
750 // corresponds to the owning thread, of which there can only
751 // be one. Thus, we are guaranteed to be providing exclusive
752 // access here which makes this safe.
753 //
754 // Also, since 'owner_val' is guaranteed to be initialized
755 // before an owned PoolGuard is created, the unwrap_unchecked
756 // is safe.
757 Err(id) => unsafe {
758 // This assert is *not* necessary for safety, since we
759 // should never be here if the guard had been put back into
760 // the pool. This is a sanity check to make sure we didn't
761 // break an internal invariant.
762 debug_assert_ne!(THREAD_ID_DROPPED, id);
763 (*self.pool.owner_val.get()).as_mut().unwrap_unchecked()
764 },
765 }
766 }
767
768 /// Consumes this guard and puts it back into the pool.
769 #[inline]
770 pub(super) fn put(this: PoolGuard<'_, T, F, MAX_POOL_STACKS>) {
771 // Since this is effectively consuming the guard and putting the
772 // value back into the pool, there's no reason to run its Drop
773 // impl after doing this. I don't believe there is a correctness
774 // problem with doing so, but there's definitely a perf problem
775 // by redoing this work. So we avoid it.
776 let mut this = core::mem::ManuallyDrop::new(this);
777 this.put_imp();
778 }
779
780 /// Puts this guard back into the pool by only borrowing the guard as
781 /// mutable. This should be called at most once.
782 #[inline(always)]
783 fn put_imp(&mut self) {
784 match core::mem::replace(&mut self.value, Err(THREAD_ID_DROPPED)) {
785 Ok(value) => {
786 // If we were told to discard this value then don't bother
787 // trying to put it back into the pool. This occurs when
788 // the pop operation failed to acquire a lock and we
789 // decided to create a new value in lieu of contending for
790 // the lock.
791 if self.discard {
792 return;
793 }
794 self.pool.put_value(value);
795 }
796 // If this guard has a value "owned" by the thread, then
797 // the Pool guarantees that this is the ONLY such guard.
798 // Therefore, in order to place it back into the pool and make
799 // it available, we need to change the owner back to the owning
800 // thread's ID. But note that we use the ID that was stored in
801 // the guard, since a guard can be moved to another thread and
802 // dropped. (A previous iteration of this code read from the
803 // THREAD_ID thread local, which uses the ID of the current
804 // thread which may not be the ID of the owning thread! This
805 // also avoids the TLS access, which is likely a hair faster.)
806 Err(owner) => {
807 // If we hit this point, it implies 'put_imp' has been
808 // called multiple times for the same guard which in turn
809 // corresponds to a bug in this implementation.
810 assert_ne!(THREAD_ID_DROPPED, owner);
811 self.pool.owner.store(owner, Ordering::Release);
812 }
813 }
814 }
815 }
816
817 impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize> Drop
818 for PoolGuard<'a, T, F, { MAX_POOL_STACKS }>
819 {
820 #[inline]
821 fn drop(&mut self) {
822 self.put_imp();
823 }
824 }
825
826 impl<
827 'a,
828 T: Send + core::fmt::Debug,
829 F: Fn() -> T,
830 const MAX_POOL_STACKS: usize,
831 > core::fmt::Debug for PoolGuard<'a, T, F, { MAX_POOL_STACKS }>
832 {
833 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
834 f.debug_struct("PoolGuard")
835 .field("pool", &self.pool)
836 .field("value", &self.value)
837 .finish()
838 }
839 }
840}
841
842// FUTURE: We should consider using Mara Bos's nearly-lock-free version of this
843// here: https://gist.github.com/m-ou-se/5fdcbdf7dcf4585199ce2de697f367a4.
844//
845// One reason why I did things with a "mutex" below is that it isolates the
846// safety concerns to just the Mutex, where as the safety of Mara's pool is a
847// bit more sprawling. I also expect this code to not be used that much, and
848// so is unlikely to get as much real world usage with which to test it. That
849// means the "obviously correct" lever is an important one.
850//
851// The specific reason to use Mara's pool is that it is likely faster and also
852// less likely to hit problems with spin-locks, although it is not completely
853// impervious to them.
854//
855// The best solution to this problem, probably, is a truly lock free pool. That
856// could be done with a lock free linked list. The issue is the ABA problem. It
857// is difficult to avoid, and doing so is complex. BUT, the upshot of that is
858// that if we had a truly lock free pool, then we could also use it above in
859// the 'std' pool instead of a Mutex because it should be completely free the
860// problems that come from spin-locks.
861#[cfg(not(feature = "std"))]
862mod inner {
863 use core::{
864 cell::UnsafeCell,
865 panic::{RefUnwindSafe, UnwindSafe},
866 sync::atomic::{AtomicBool, Ordering},
867 };
868
869 use alloc::{boxed::Box, vec, vec::Vec};
870
871 /// A thread safe pool utilizing alloc-only features.
872 ///
873 /// Unlike the std version, it doesn't seem possible(?) to implement the
874 /// "thread owner" optimization because alloc-only doesn't have any concept
875 /// of threads. So the best we can do is just a normal stack. This will
876 /// increase latency in alloc-only environments.
877 pub(super) struct Pool<T, F, const MAX_POOL_STACKS: usize> {
878 /// A stack of T values to hand out. These are used when a Pool is
879 /// accessed by a thread that didn't create it.
880 stack: Mutex<Vec<Box<T>>>,
881 /// A function to create more T values when stack is empty and a caller
882 /// has requested a T.
883 create: F,
884 }
885
886 // If T is UnwindSafe, then since we provide exclusive access to any
887 // particular value in the pool, it should therefore also be considered
888 // RefUnwindSafe.
889 impl<T: UnwindSafe, F: UnwindSafe, const MAX_POOL_STACKS: usize>
890 RefUnwindSafe for Pool<T, F, MAX_POOL_STACKS>
891 {
892 }
893
894 impl<T, F, const MAX_POOL_STACKS: usize> Pool<T, F, MAX_POOL_STACKS> {
895 /// Create a new pool. The given closure is used to create values in
896 /// the pool when necessary.
897 pub(super) const fn new(create: F) -> Pool<T, F, MAX_POOL_STACKS> {
898 Pool { stack: Mutex::new(vec![]), create }
899 }
900 }
901
902 impl<T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
903 Pool<T, F, MAX_POOL_STACKS>
904 {
905 /// Get a value from the pool. This may block if another thread is also
906 /// attempting to retrieve a value from the pool.
907 #[inline]
908 pub(super) fn get(&self) -> PoolGuard<'_, T, F, MAX_POOL_STACKS> {
909 let mut stack = self.stack.lock();
910 let value = match stack.pop() {
911 None => Box::new((self.create)()),
912 Some(value) => value,
913 };
914 PoolGuard { pool: self, value: Some(value) }
915 }
916
917 /// Puts a value back into the pool. Callers don't need to call this.
918 /// Once the guard that's returned by 'get' is dropped, it is put back
919 /// into the pool automatically.
920 #[inline]
921 fn put_value(&self, value: Box<T>) {
922 let mut stack = self.stack.lock();
923 stack.push(value);
924 }
925 }
926
927 impl<T: core::fmt::Debug, F, const MAX_POOL_STACKS: usize>
928 core::fmt::Debug for Pool<T, F, MAX_POOL_STACKS>
929 {
930 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
931 f.debug_struct("Pool").field("stack", &self.stack).finish()
932 }
933 }
934
935 /// A guard that is returned when a caller requests a value from the pool.
936 pub(super) struct PoolGuard<
937 'a,
938 T: Send,
939 F: Fn() -> T,
940 const MAX_POOL_STACKS: usize,
941 > {
942 /// The pool that this guard is attached to.
943 pool: &'a Pool<T, F, MAX_POOL_STACKS>,
944 /// This is None after the guard has been put back into the pool.
945 value: Option<Box<T>>,
946 }
947
948 impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize>
949 PoolGuard<'a, T, F, MAX_POOL_STACKS>
950 {
951 /// Return the underlying value.
952 #[inline]
953 pub(super) fn value(&self) -> &T {
954 self.value.as_deref().unwrap()
955 }
956
957 /// Return the underlying value as a mutable borrow.
958 #[inline]
959 pub(super) fn value_mut(&mut self) -> &mut T {
960 self.value.as_deref_mut().unwrap()
961 }
962
963 /// Consumes this guard and puts it back into the pool.
964 #[inline]
965 pub(super) fn put(this: PoolGuard<'_, T, F, MAX_POOL_STACKS>) {
966 // Since this is effectively consuming the guard and putting the
967 // value back into the pool, there's no reason to run its Drop
968 // impl after doing this. I don't believe there is a correctness
969 // problem with doing so, but there's definitely a perf problem
970 // by redoing this work. So we avoid it.
971 let mut this = core::mem::ManuallyDrop::new(this);
972 this.put_imp();
973 }
974
975 /// Puts this guard back into the pool by only borrowing the guard as
976 /// mutable. This should be called at most once.
977 #[inline(always)]
978 fn put_imp(&mut self) {
979 if let Some(value) = self.value.take() {
980 self.pool.put_value(value);
981 }
982 }
983 }
984
985 impl<'a, T: Send, F: Fn() -> T, const MAX_POOL_STACKS: usize> Drop
986 for PoolGuard<'a, T, F, MAX_POOL_STACKS>
987 {
988 #[inline]
989 fn drop(&mut self) {
990 self.put_imp();
991 }
992 }
993
994 impl<
995 'a,
996 T: Send + core::fmt::Debug,
997 F: Fn() -> T,
998 const MAX_POOL_STACKS: usize,
999 > core::fmt::Debug for PoolGuard<'a, T, F, MAX_POOL_STACKS>
1000 {
1001 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1002 f.debug_struct("PoolGuard")
1003 .field("pool", &self.pool)
1004 .field("value", &self.value)
1005 .finish()
1006 }
1007 }
1008
1009 /// A spin-lock based mutex. Yes, I have read spinlocks cosnidered
1010 /// harmful[1], and if there's a reasonable alternative choice, I'll
1011 /// happily take it.
1012 ///
1013 /// I suspect the most likely alternative here is a Treiber stack, but
1014 /// implementing one correctly in a way that avoids the ABA problem looks
1015 /// subtle enough that I'm not sure I want to attempt that. But otherwise,
1016 /// we only need a mutex in order to implement our pool, so if there's
1017 /// something simpler we can use that works for our `Pool` use case, then
1018 /// that would be great.
1019 ///
1020 /// Note that this mutex does not do poisoning.
1021 ///
1022 /// [1]: https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html
1023 #[derive(Debug)]
1024 struct Mutex<T> {
1025 locked: AtomicBool,
1026 data: UnsafeCell<T>,
1027 }
1028
1029 // SAFETY: Since a Mutex guarantees exclusive access, as long as we can
1030 // send it across threads, it must also be Sync.
1031 unsafe impl<T: Send> Sync for Mutex<T> {}
1032
1033 impl<T> Mutex<T> {
1034 /// Create a new mutex for protecting access to the given value across
1035 /// multiple threads simultaneously.
1036 const fn new(value: T) -> Mutex<T> {
1037 Mutex {
1038 locked: AtomicBool::new(false),
1039 data: UnsafeCell::new(value),
1040 }
1041 }
1042
1043 /// Lock this mutex and return a guard providing exclusive access to
1044 /// `T`. This blocks if some other thread has already locked this
1045 /// mutex.
1046 #[inline]
1047 fn lock(&self) -> MutexGuard<'_, T> {
1048 while self
1049 .locked
1050 .compare_exchange(
1051 false,
1052 true,
1053 Ordering::AcqRel,
1054 Ordering::Acquire,
1055 )
1056 .is_err()
1057 {
1058 core::hint::spin_loop();
1059 }
1060 // SAFETY: The only way we're here is if we successfully set
1061 // 'locked' to true, which implies we must be the only thread here
1062 // and thus have exclusive access to 'data'.
1063 let data = unsafe { &mut *self.data.get() };
1064 MutexGuard { locked: &self.locked, data }
1065 }
1066 }
1067
1068 /// A guard that derefs to &T and &mut T. When it's dropped, the lock is
1069 /// released.
1070 #[derive(Debug)]
1071 struct MutexGuard<'a, T> {
1072 locked: &'a AtomicBool,
1073 data: &'a mut T,
1074 }
1075
1076 impl<'a, T> core::ops::Deref for MutexGuard<'a, T> {
1077 type Target = T;
1078
1079 #[inline]
1080 fn deref(&self) -> &T {
1081 self.data
1082 }
1083 }
1084
1085 impl<'a, T> core::ops::DerefMut for MutexGuard<'a, T> {
1086 #[inline]
1087 fn deref_mut(&mut self) -> &mut T {
1088 self.data
1089 }
1090 }
1091
1092 impl<'a, T> Drop for MutexGuard<'a, T> {
1093 #[inline]
1094 fn drop(&mut self) {
1095 // Drop means 'data' is no longer accessible, so we can unlock
1096 // the mutex.
1097 self.locked.store(false, Ordering::Release);
1098 }
1099 }
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104 use core::panic::{RefUnwindSafe, UnwindSafe};
1105
1106 use alloc::{boxed::Box, vec, vec::Vec};
1107
1108 use super::*;
1109
1110 #[test]
1111 fn oibits() {
1112 fn assert_oitbits<T: Send + Sync + UnwindSafe + RefUnwindSafe>() {}
1113 assert_oitbits::<Pool<Vec<u32>>>();
1114 assert_oitbits::<Pool<core::cell::RefCell<Vec<u32>>>>();
1115 assert_oitbits::<
1116 Pool<
1117 Vec<u32>,
1118 Box<
1119 dyn Fn() -> Vec<u32>
1120 + Send
1121 + Sync
1122 + UnwindSafe
1123 + RefUnwindSafe,
1124 >,
1125 >,
1126 >();
1127 }
1128
1129 // Tests that Pool implements the "single owner" optimization. That is, the
1130 // thread that first accesses the pool gets its own copy, while all other
1131 // threads get distinct copies.
1132 #[cfg(feature = "std")]
1133 #[test]
1134 fn thread_owner_optimization() {
1135 use std::{cell::RefCell, sync::Arc, vec};
1136
1137 let pool: Arc<Pool<RefCell<Vec<char>>>> =
1138 Arc::new(Pool::new(|| RefCell::new(vec!['a'])));
1139 pool.get().borrow_mut().push('x');
1140
1141 let pool1 = pool.clone();
1142 let t1 = std::thread::spawn(move || {
1143 let guard = pool1.get();
1144 guard.borrow_mut().push('y');
1145 });
1146
1147 let pool2 = pool.clone();
1148 let t2 = std::thread::spawn(move || {
1149 let guard = pool2.get();
1150 guard.borrow_mut().push('z');
1151 });
1152
1153 t1.join().unwrap();
1154 t2.join().unwrap();
1155
1156 // If we didn't implement the single owner optimization, then one of
1157 // the threads above is likely to have mutated the [a, x] vec that
1158 // we stuffed in the pool before spawning the threads. But since
1159 // neither thread was first to access the pool, and because of the
1160 // optimization, we should be guaranteed that neither thread mutates
1161 // the special owned pool value.
1162 //
1163 // (Technically this is an implementation detail and not a contract of
1164 // Pool's API.)
1165 assert_eq!(vec!['a', 'x'], *pool.get().borrow());
1166 }
1167
1168 // This tests that if the "owner" of a pool asks for two values, then it
1169 // gets two distinct values and not the same one. This test failed in the
1170 // course of developing the pool, which in turn resulted in UB because it
1171 // permitted getting aliasing &mut borrows to the same place in memory.
1172 #[test]
1173 fn thread_owner_distinct() {
1174 let pool = Pool::<_, _, 8>::new(|| vec!['a']);
1175
1176 {
1177 let mut g1 = pool.get();
1178 let v1 = &mut *g1;
1179 let mut g2 = pool.get();
1180 let v2 = &mut *g2;
1181 v1.push('b');
1182 v2.push('c');
1183 assert_eq!(&mut vec!['a', 'b'], v1);
1184 assert_eq!(&mut vec!['a', 'c'], v2);
1185 }
1186 // This isn't technically guaranteed, but we
1187 // expect to now get the "owned" value (the first
1188 // call to 'get()' above) now that it's back in
1189 // the pool.
1190 assert_eq!(&mut vec!['a', 'b'], &mut *pool.get());
1191 }
1192
1193 // This tests that we can share a guard with another thread, mutate the
1194 // underlying value and everything works. This failed in the course of
1195 // developing a pool since the pool permitted 'get()' to return the same
1196 // value to the owner thread, even before the previous value was put back
1197 // into the pool. This in turn resulted in this test producing a data race.
1198 #[cfg(feature = "std")]
1199 #[test]
1200 fn thread_owner_sync() {
1201 let pool = Pool::<_, _, 8>::new(|| vec!['a']);
1202 {
1203 let mut g1 = pool.get();
1204 let mut g2 = pool.get();
1205 std::thread::scope(|s| {
1206 s.spawn(|| {
1207 g1.push('b');
1208 });
1209 s.spawn(|| {
1210 g2.push('c');
1211 });
1212 });
1213
1214 let v1 = &mut *g1;
1215 let v2 = &mut *g2;
1216 assert_eq!(&mut vec!['a', 'b'], v1);
1217 assert_eq!(&mut vec!['a', 'c'], v2);
1218 }
1219
1220 // This isn't technically guaranteed, but we
1221 // expect to now get the "owned" value (the first
1222 // call to 'get()' above) now that it's back in
1223 // the pool.
1224 assert_eq!(&mut vec!['a', 'b'], &mut *pool.get());
1225 }
1226
1227 // This tests that if we move a PoolGuard that is owned by the current
1228 // thread to another thread and drop it, then the thread owner doesn't
1229 // change. During development of the pool, this test failed because the
1230 // PoolGuard assumed it was dropped in the same thread from which it was
1231 // created, and thus used the current thread's ID as the owner, which could
1232 // be different than the actual owner of the pool.
1233 #[cfg(feature = "std")]
1234 #[test]
1235 fn thread_owner_send_drop() {
1236 let pool = Pool::<_, _, 8>::new(|| vec!['a']);
1237 // Establishes this thread as the owner.
1238 {
1239 pool.get().push('b');
1240 }
1241 std::thread::scope(|s| {
1242 // Sanity check that we get the same value back.
1243 // (Not technically guaranteed.)
1244 let mut g = pool.get();
1245 assert_eq!(&vec!['a', 'b'], &*g);
1246 // Now push it to another thread and drop it.
1247 s.spawn(move || {
1248 g.push('c');
1249 })
1250 .join()
1251 .unwrap();
1252 });
1253 // Now check that we're still the owner. This is not technically
1254 // guaranteed by the API, but is true in practice given the thread
1255 // owner optimization.
1256 assert_eq!(&vec!['a', 'b', 'c'], &*pool.get());
1257 }
1258}