Skip to content

Commit

Permalink
Remove incorrect thread_id::try_get function
Browse files Browse the repository at this point in the history
This was introduced in #44 but is actually broken since a thread could
be assigned the ID of an existing slot in the table if another thread
previously using that ID has exited.
  • Loading branch information
Amanieu committed Feb 10, 2023
1 parent 63c4c62 commit b45a736
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 32 deletions.
11 changes: 5 additions & 6 deletions src/lib.rs
Expand Up @@ -190,7 +190,7 @@ impl<T: Send> ThreadLocal<T> {

/// Returns the element for the current thread, if it exists.
pub fn get(&self) -> Option<&T> {
thread_id::try_get().and_then(|thread| self.get_inner(thread))
self.get_inner(thread_id::get())
}

/// Returns the element for the current thread, or creates it if it doesn't
Expand All @@ -212,12 +212,11 @@ impl<T: Send> ThreadLocal<T> {
where
F: FnOnce() -> Result<T, E>,
{
let thread = thread_id::try_get();
if let Some(thread) = thread {
if let Some(val) = self.get_inner(thread) {
return Ok(val);
}
let thread = thread_id::get();
if let Some(val) = self.get_inner(thread) {
return Ok(val);
}

Ok(self.insert(create()?))
}

Expand Down
48 changes: 22 additions & 26 deletions src/thread_id.rs
Expand Up @@ -97,29 +97,26 @@ cfg_if::cfg_if! {
}
}

/// Attempts to get the current thread if `get` has previously been
/// called.
#[inline]
pub(crate) fn try_get() -> Option<Thread> {
unsafe {
THREAD
}
}

/// Returns a thread ID for the current thread, allocating one if needed.
#[inline]
pub(crate) fn get() -> Thread {
if let Some(thread) = unsafe { THREAD } {
thread
} else {
let new = Thread::new(THREAD_ID_MANAGER.lock().unwrap().alloc());
unsafe {
THREAD = Some(new);
}
THREAD_GUARD.with(|_| {});
new
get_slow()
}
}

/// Out-of-line slow path for allocating a thread ID.
#[cold]
fn get_slow() -> Thread {
let new = Thread::new(THREAD_ID_MANAGER.lock().unwrap().alloc());
unsafe {
THREAD = Some(new);
}
THREAD_GUARD.with(|_| {});
new
}
} else {
use std::cell::Cell;

Expand All @@ -140,27 +137,26 @@ cfg_if::cfg_if! {
}
}

/// Attempts to get the current thread if `get` has previously been
/// called.
#[inline]
pub(crate) fn try_get() -> Option<Thread> {
THREAD.with(|thread| thread.get())
}

/// Returns a thread ID for the current thread, allocating one if needed.
#[inline]
pub(crate) fn get() -> Thread {
THREAD.with(|thread| {
if let Some(thread) = thread.get() {
thread
} else {
let new = Thread::new(THREAD_ID_MANAGER.lock().unwrap().alloc());
thread.set(Some(new));
THREAD_GUARD.with(|_| {});
new
get_slow(thread)
}
})
}

/// Out-of-line slow path for allocating a thread ID.
#[cold]
fn get_slow(thread: &Cell<Option<Thread>>) -> Thread {
let new = Thread::new(THREAD_ID_MANAGER.lock().unwrap().alloc());
thread.set(Some(new));
THREAD_GUARD.with(|_| {});
new
}
}
}

Expand Down

0 comments on commit b45a736

Please sign in to comment.