Skip to content

Commit

Permalink
add inherit_task_local for spawn_blocking, bump version to 0.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Xaeroxe committed May 8, 2024
1 parent 9a0fc45 commit af98abd
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
19 changes: 18 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "tokio-inherit-task-local"
description = "Task local variables for tokio that can be inherited across a spawn"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
repository = "https://github.com/Xaeroxe/tokio-inherit-task-local"
documentation = "https://docs.rs/tokio-inherit-task-local"
Expand All @@ -13,4 +13,4 @@ const-random = "0.1.18"
tokio = { version = "1.37.0", features = ["rt"] }

[dev-dependencies]
tokio = { version = "1.37.0", features = ["rt", "macros"]}
tokio = { version = "1.37.0", features = ["rt", "rt-multi-thread", "macros"]}
26 changes: 26 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,32 @@ where
}
}

/// Returns a closure which has its own copy of the current table for inheritable task locals.
/// Intended for use with [`tokio::task::spawn_blocking`].
///
/// # Example
/// ```
/// use tokio_inherit_task_local::{inherit_task_local, inheritable_task_local};
///
/// inheritable_task_local! {
/// static NUMBER: u32;
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let output = NUMBER.scope(1, async move {
/// tokio::task::spawn_blocking(inherit_task_local(|| NUMBER.get())).await.unwrap()
/// }).await;
/// assert_eq!(output, 1);

Check warning on line 110 in src/lib.rs

View workflow job for this annotation

GitHub Actions / Rustfmt [Formatter]

Diff in /home/runner/work/tokio-inherit-task-local/tokio-inherit-task-local/src/lib.rs

Check warning on line 110 in src/lib.rs

View workflow job for this annotation

GitHub Actions / Rustfmt [Formatter]

Diff in /home/runner/work/tokio-inherit-task-local/tokio-inherit-task-local/src/lib.rs
/// }
/// ```
pub fn inherit_task_local<F, R>(f: F) -> impl FnOnce() -> R + Send + 'static where F: FnOnce() -> R + Send + 'static {
let new_task_locals = INHERITABLE_TASK_LOCALS
.try_with(|task_locals| task_locals.clone())
.unwrap_or_else(|_| TaskLocalInheritableTable::new(HashMap::new()));
move || INHERITABLE_TASK_LOCALS.sync_scope(new_task_locals, f)
}

tokio::task_local! {
static INHERITABLE_TASK_LOCALS: TaskLocalInheritableTable
}
Expand Down

0 comments on commit af98abd

Please sign in to comment.