backdrop/tokio.rs
1//! The contents of this module are only available when the `tokio` feature is enabled.
2use crate::{Backdrop, BackdropStrategy};
3
4/// Strategy which spawns a new tokio task which drops the contained value.
5///
6/// This only works within the context of a Tokio runtime.
7/// (Dropping objects constructed with this strategy while no Tokio runtime is available
8/// will result in a panic!)
9///
10/// Since the overhead of creating new Tokio tasks is very small, this is really fast
11/// (at least from the perspective of the current task.)
12///
13/// Note that if dropping your value takes a very long time, you might be better off
14/// using [`TokioBlockingTaskStrategy`] instead. Benchmark!
15pub struct TokioTaskStrategy();
16impl<T: Send + 'static> BackdropStrategy<T> for TokioTaskStrategy {
17 #[inline]
18 fn execute(droppable: T) {
19 tokio::task::spawn(async move {
20 core::mem::drop(droppable);
21 });
22 }
23}
24
25/// Convenient alias for a [`Backdrop`] that uses the [`TokioTaskStrategy`]
26pub type TokioTaskBackdrop<T> = Backdrop<T, TokioTaskStrategy>;
27
28/// Strategy which spawns a new 'blocking' tokio task which drops the contained value.
29///
30/// This only works within the context of a Tokio runtime.
31/// (Dropping objects constructed with this strategy while no Tokio runtime is available
32/// will result in a panic!)
33///
34/// This strategy is similar to [`TokioTaskStrategy`] but uses [`tokio::task::spawn_blocking`]
35/// instead. This makes sure that the 'fast async tasks' thread pool can continue its normal work,
36/// because the drop work is passed to the 'ok to block here' thread pool.
37///
38/// Benchmark to find out which approach suits your scenario better!
39pub struct TokioBlockingTaskStrategy();
40impl<T: Send + 'static> BackdropStrategy<T> for TokioBlockingTaskStrategy {
41 #[inline]
42 fn execute(droppable: T) {
43 tokio::task::spawn_blocking(move || core::mem::drop(droppable));
44 }
45}
46
47/// Convenient alias for a [`Backdrop`] that uses the [`TokioBlockingTaskStrategy`]
48pub type TokioBlockingTaskBackdrop<T> = Backdrop<T, TokioBlockingTaskStrategy>;
49