Skip to content

Thread local try with #43158

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

Merged
merged 4 commits into from
Jul 13, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions src/libstd/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use io::{self, Initializer, BufReader, LineWriter};
use sync::{Arc, Mutex, MutexGuard};
use sys::stdio;
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
use thread::{LocalKey, LocalKeyState};
use thread::LocalKey;

/// Stdout used by print! and println! macros
thread_local! {
Expand Down Expand Up @@ -674,20 +674,14 @@ fn print_to<T>(args: fmt::Arguments,
local_s: &'static LocalKey<RefCell<Option<Box<Write+Send>>>>,
global_s: fn() -> T,
label: &str) where T: Write {
let result = match local_s.state() {
LocalKeyState::Uninitialized |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't quite the same behavior as before because Uninitialized would route to the global logger whereas this implementation would lazily run initialization and then route to the global logger.

LocalKeyState::Destroyed => global_s().write_fmt(args),
LocalKeyState::Valid => {
local_s.with(|s| {
if let Ok(mut borrowed) = s.try_borrow_mut() {
if let Some(w) = borrowed.as_mut() {
return w.write_fmt(args);
}
}
global_s().write_fmt(args)
})
let result = local_s.try_with(|s| {
if let Ok(mut borrowed) = s.try_borrow_mut() {
if let Some(w) = borrowed.as_mut() {
return w.write_fmt(args);
}
}
};
global_s().write_fmt(args)
}).unwrap_or_else(|_| global_s().write_fmt(args));
if let Err(e) = result {
panic!("failed printing to {}: {}", label, e);
}
Expand Down
11 changes: 3 additions & 8 deletions src/libstd/sys_common/thread_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

use cell::RefCell;
use thread::Thread;
use thread::LocalKeyState;

struct ThreadInfo {
stack_guard: Option<usize>,
Expand All @@ -23,19 +22,15 @@ thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(N

impl ThreadInfo {
fn with<R, F>(f: F) -> Option<R> where F: FnOnce(&mut ThreadInfo) -> R {
if THREAD_INFO.state() == LocalKeyState::Destroyed {
return None
}

THREAD_INFO.with(move |c| {
THREAD_INFO.try_with(move |c| {
if c.borrow().is_none() {
*c.borrow_mut() = Some(ThreadInfo {
stack_guard: None,
thread: Thread::new(None),
})
}
Some(f(c.borrow_mut().as_mut().unwrap()))
})
f(c.borrow_mut().as_mut().unwrap())
}).ok()
}
}

Expand Down
52 changes: 52 additions & 0 deletions src/libstd/thread/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,32 @@ pub enum LocalKeyState {
Destroyed,
}

/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
pub struct AccessError {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you reexport this outside the local module?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, but comment not marked as outdated.

_private: (),
}

#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
impl fmt::Debug for AccessError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("AccessError").finish()
}
}

#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt("already destroyed", f)
}
}

impl<T: 'static> LocalKey<T> {
#[doc(hidden)]
#[unstable(feature = "thread_local_internals",
Expand Down Expand Up @@ -331,6 +357,32 @@ impl<T: 'static> LocalKey<T> {
}
}
}

/// Acquires a reference to the value in this TLS key.
///
/// This will lazily initialize the value if this thread has not referenced
/// this key yet. If the key has been destroyed (which may happen if this is called
/// in a destructor), this function will return a ThreadLocalError.
///
/// # Panics
///
/// This function will still `panic!()` if the key is uninitialized and the
/// key's initializer panics.
#[unstable(feature = "thread_local_state",
reason = "state querying was recently added",
issue = "27716")]
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
where F: FnOnce(&T) -> R {
unsafe {
let slot = (self.inner)().ok_or(AccessError {
_private: (),
})?;
Ok(f(match *slot.get() {
Some(ref inner) => inner,
None => self.init(slot),
}))
}
}
}

#[doc(hidden)]
Expand Down
33 changes: 33 additions & 0 deletions src/test/run-pass/tls-try-with.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-emscripten no threads support

#![feature(thread_local_state)]

use std::thread;

struct Foo;

thread_local!(static FOO: Foo = Foo {});

impl Drop for Foo {
fn drop(&mut self) {
assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add an assertion that this code is run as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, but comment not marked as outdated.

}
}

fn main() {
thread::spawn(|| {
assert_eq!(FOO.try_with(|_| {
132
}).expect("`try_with` failed"), 132);
}).join().unwrap();
}