Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add LocalSet::enter #4765

Merged
merged 14 commits into from Jul 13, 2022
13 changes: 13 additions & 0 deletions tokio/src/task/local.rs
Expand Up @@ -319,6 +319,11 @@ const MAX_TASKS_PER_TICK: usize = 61;
/// How often it check the remote queue first.
const REMOTE_FIRST_INTERVAL: u8 = 31;

#[derive(Debug)]
pub struct LocalEnterGuard<'a> {
_guard: &'a LocalSet,
}

impl LocalSet {
/// Returns a new local task set.
pub fn new() -> LocalSet {
Expand All @@ -336,6 +341,14 @@ impl LocalSet {
}
}

/// Enter current LocalSet context
pub fn enter(&self) -> LocalEnterGuard<'_> {
CURRENT.inner.with(|c| {
c.set(&self.context as *const _ as *const ());
LocalEnterGuard { _guard: &self }
})
}
gftea marked this conversation as resolved.
Show resolved Hide resolved

/// Spawns a `!Send` task onto the local task set.
///
/// This task is guaranteed to be run on the current thread.
Expand Down
2 changes: 1 addition & 1 deletion tokio/src/task/mod.rs
Expand Up @@ -297,7 +297,7 @@ cfg_rt! {
}

mod local;
pub use local::{spawn_local, LocalSet};
pub use local::{spawn_local, LocalSet, LocalEnterGuard};

mod task_local;
pub use task_local::LocalKey;
Expand Down
15 changes: 15 additions & 0 deletions tokio/tests/task_local_set.rs
Expand Up @@ -126,6 +126,21 @@ async fn local_threadpool_timer() {
})
.await;
}
#[test]
fn enter_guard_spawn() {
let local = LocalSet::new();
let _guard = local.enter();
// Run the local task set.

let join = task::spawn_local(async { true });
let rt = runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
local.block_on(&rt, async move {
assert!(join.await.unwrap());
});
}

#[test]
// This will panic, since the thread that calls `block_on` cannot use
Expand Down