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

task: ignore failure to set TLS in LocalSet Drop #4976

Merged
merged 3 commits into from Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 32 additions & 1 deletion tokio/src/task/local.rs
Expand Up @@ -633,6 +633,37 @@ impl LocalSet {
f()
})
}

/// This method is like `with`, but it just calls `f` without setting the thread-local if that
/// fails.
fn with_if_possible<T>(&self, f: impl FnOnce() -> T) -> T {
let mut f = Some(f);

let res = CURRENT.try_with(|ctx| {
struct Reset<'a> {
ctx_ref: &'a Cell<Option<Rc<Context>>>,
val: Option<Rc<Context>>,
}
impl<'a> Drop for Reset<'a> {
fn drop(&mut self) {
self.ctx_ref.replace(self.val.take());
}
}
let old = ctx.replace(Some(self.context.clone()));

let _reset = Reset {
ctx_ref: ctx,
val: old,
};

(f.take().unwrap())()
});

match res {
Ok(res) => res,
Err(_access_error) => (f.take().unwrap())(),
}
}
}

cfg_unstable! {
Expand Down Expand Up @@ -744,7 +775,7 @@ impl Default for LocalSet {

impl Drop for LocalSet {
fn drop(&mut self) {
self.with(|| {
self.with_if_possible(|| {
// Shut down all tasks in the LocalOwnedTasks and close it to
// prevent new tasks from ever being added.
self.context.owned.close_and_shutdown_all();
Expand Down
21 changes: 21 additions & 0 deletions tokio/tests/task_local_set.rs
Expand Up @@ -311,6 +311,27 @@ fn join_local_future_elsewhere() {
});
}

// Tests for <https://github.com/tokio-rs/tokio/issues/4973>
#[cfg(not(tokio_wasi))] // Wasi doesn't support threads
#[tokio::test(flavor = "multi_thread")]
async fn localset_in_thread_local() {
thread_local! {
static LOCAL_SET: LocalSet = LocalSet::new();
}

// holds runtime thread until end of main fn.
let (_tx, rx) = oneshot::channel::<()>();
let handle = tokio::runtime::Handle::current();

std::thread::spawn(move || {
LOCAL_SET.with(|local_set| {
handle.block_on(local_set.run_until(async move {
let _ = rx.await;
}))
});
});
}

#[test]
fn drop_cancels_tasks() {
use std::rc::Rc;
Expand Down