Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 4 additions & 1 deletion library/std/src/thread/current.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,9 @@ pub(crate) fn current_or_unnamed() -> Thread {
(*current).clone()
}
} else if current == DESTROYED {
Thread::new(id::get_or_init(), None)
let thread = Thread::new(id::get_or_init(), None);
thread.set_os_id_to_current();

@Darksonn Darksonn Jul 31, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why doesn't Thread::new just call set_os_id_to_current internally?

If there are callers where this doesn't work, maybe we should have two constructors?

  • Thread::new_current uses current OS id
  • Thread::new_remote takes OS id as paramter

I think this would also avoid the OnceLock.

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I added Thread::new_current just for the current path, however I think we couldn't get rid of sync primitives for os_id because of the spawn_unchecked path, in that case when we create the Thread, we are still running on parent thread, so using set_os_id_to_current would assign parent os_id to child thread that it is trying to spawn.

  1. Thread::new lifecycle.rs:48 (imp::current_os_id() returns the parent's TID)
  2. imp::Thread::new lifecycle.rs:116

thread
} else {
init_current(current)
}
Expand Down Expand Up @@ -292,6 +294,7 @@ fn init_current(current: *mut ()) -> Thread {
// If the thread ID was initialized already, use it.
let id = id::get_or_init();
let thread = Thread::new(id, None);
thread.set_os_id_to_current();

// Make sure that `crate::rt::thread_cleanup` will be run, which will
// call `drop_current`.
Expand Down
4 changes: 4 additions & 0 deletions library/std/src/thread/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ impl ThreadInit {
rtabort!("current thread handle already set during thread spawn");
}

// The handle was created by the spawning thread, so only now that we are
// running can the OS id be filled in.
self.handle.set_os_id_to_current();

if let Some(name) = self.handle.cname() {
imp::set_name(name);
}
Expand Down
13 changes: 13 additions & 0 deletions library/std/src/thread/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,19 @@ fn test_thread_os_id_not_equal() {
assert!(current_id != spawned_id);
}

#[test]
fn test_thread_os_id_matches_current() {
assert_eq!(thread::current().os_id(), crate::sys::thread::current_os_id());
}

#[test]
fn test_thread_os_id_of_spawned_thread() {
let spawned = thread::spawn(|| thread::current().os_id());
let handle = spawned.thread().clone();
let seen_by_the_thread_itself = spawned.join().unwrap();
assert_eq!(handle.os_id(), seen_by_the_thread_itself);
}

#[test]
fn test_scoped_threads_drop_result_before_join() {
let actually_finished = &AtomicBool::new(false);
Expand Down
96 changes: 96 additions & 0 deletions library/std/src/thread/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::fmt;
use crate::pin::Pin;
use crate::sync::Arc;
use crate::sys::sync::Parker;
use crate::sys::thread as imp;
use crate::time::Duration;

// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
Expand Down Expand Up @@ -40,6 +41,59 @@ mod thread_name_string {

use thread_name_string::ThreadNameString;

// The handle of a spawned thread exists before the thread does, so the thread
// stores its own id once it starts running, hence the atomic. 0 means "not known".

@joboet joboet Jul 30, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nothing guarantees that the OS's ID is non-zero, we really shouldn't use zero as a sentinel.

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Switched to OnceLock: write-once without a sentinel, and it needs no 64-bit atomic so the cfg_select is gone too.

Waiting would need the child to always store the value, so OnceLock<Option>.
I'm also not sure how it works out for spawn hooks, which get &Thread on the parent before the thread exists.
You mentioned you have an implementation, so if you've already worked that out I'd rather build on it than guess.

//
// Of the platform calls behind `current_os_id`, only Apple's yields a `uint64_t`,
// and every Apple target has 64-bit atomics, so `usize` loses nothing on the
// second arm.
cfg_select! {
target_has_atomic = "64" => {
use crate::sync::atomic::{Atomic, AtomicU64, Ordering::Relaxed};

struct OsId(Atomic<u64>);

impl OsId {
const fn unknown() -> Self {
Self(AtomicU64::new(0))
}

fn get(&self) -> Option<u64> {
match self.0.load(Relaxed) {
0 => None,
id => Some(id),
}
}

fn set(&self, id: u64) {
self.0.store(id, Relaxed);
}
}
}
_ => {
use crate::sync::atomic::{Atomic, AtomicUsize, Ordering::Relaxed};

struct OsId(Atomic<usize>);

impl OsId {
const fn unknown() -> Self {
Self(AtomicUsize::new(0))
}

fn get(&self) -> Option<u64> {
match self.0.load(Relaxed) {
0 => None,
id => Some(id as u64),
}
}

fn set(&self, id: u64) {
self.0.store(id as usize, Relaxed);
}
}
}
}

/// The internal representation of a `Thread` handle
///
/// We explicitly set the alignment for our guarantee in Thread::into_raw. This
Expand All @@ -49,6 +103,7 @@ use thread_name_string::ThreadNameString;
struct Inner {
name: Option<ThreadNameString>,
id: ThreadId,
os_id: OsId,
parker: Parker,
}

Expand Down Expand Up @@ -103,13 +158,25 @@ impl Thread {
let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
(&raw mut (*ptr).name).write(name);
(&raw mut (*ptr).id).write(id);
(&raw mut (*ptr).os_id).write(OsId::unknown());
Parker::new_in_place(&raw mut (*ptr).parker);
Pin::new_unchecked(arc.assume_init())
};

Thread { inner }
}

/// Records the OS id of the calling thread in this handle.
///
/// May only be called from the thread to which this handle belongs. A
/// spawned thread does this itself once it starts running, since its handle
/// already exists by then.
pub(crate) fn set_os_id_to_current(&self) {
if let Some(os_id) = imp::current_os_id() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The SGX impl of current_os_id appears to return the address of thread::current()'s allocated Arc<Thread> if I'm reading it right. I think under the current design, that allocation is not guaranteed to exist and so this will hit the BUSY / re-entrant case in thread::current?

Specifically the sequence is:

  • Foreign spawn -- e.g. via pthread, not spawn_unchecked
  • Thread runs and calls thread::current()
  • Calls Thread::new_current
  • Calls imp::current_os_id
  • Calls thread::current()

(On the spawn_unchecked path we'd set_current before we hit this code).

I think the two fixes are either (a) we modify thread::current() to call set_os_id after initializing the thread-local pointer to Arc or (b) we change SGX to have some other implementation (e.g. use the Rust ID).

cc @jethrogb @raoulstrackx @aditijannu (sgx target maintainers), in case you have an opinion on the "OS" IDs of threads for the target (https://doc.rust-lang.org/nightly/rustc/platform-support/x86_64-fortanix-unknown-sgx.html).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That thread::current() in SGX isn't std::thread::current
sgx.rs imports thread from crate::sys::pal::abi, so it resolves to abi/thread.rs. So I don't see the path that will hit the BUSY case in std::thread::current.

I went through every current_os_id impl and none calls std::thread::current, it may only be true for today, so I've documented it on set_os_id_to_current:

imp::current_os_id must not allocate with the global allocator or call thread::current.

Not sure that's the right place to document this.

On reordering: putting set_os_id after initializing the thread-local pointer to Arc, could help to drop these constraint, so some platforms may use std::thread::current in imp::current_os_id, I don't see any need in it beyond future-proofing, however I may be missing something.

It also wouldn't cover the DESTROYED branch of current_or_unnamed, where the handle is a temporary that never goes into CURRENT.

self.inner.os_id.set(os_id);
}
}

/// Like the public [`park`], but callable on any handle. This is used to
/// allow parking in TLS destructors.
///
Expand Down Expand Up @@ -204,6 +271,35 @@ impl Thread {
self.inner.id
}

/// Gets the id the operating system gave this thread, if it has one that can
/// be read.
///
/// This is the id `ps`, `top`, a debugger or a crash log shows, unlike
/// [`ThreadId`], which is internal to Rust and unrelated to it. `None` means
/// the platform has no such id or offers no way to read it, or that the
/// thread has not started running yet.
///
/// The operating system may hand the same id to a later thread once this one
/// exits, so it does not name a thread uniquely over the life of the
/// process. It may also no longer refer to this thread at all, since any
/// thread but the current one can exit at any point. For anything other than
/// the current thread, logging is the only safe use.

@tgross35 tgross35 Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It's usable for any thread that is running, not just the current right?

I think the property to convey is that OS TIDs uniquely represent a thread among other running threads, which effectively means that if a thread isn't known to be running then ID can only be used in cases where non-uniqueness is okay (e.g. logging). And then one way to know the thread is running is if you're looking at the current thread's ID.

Not sure how best to put this into words.

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

So there are conditions under which it is safe to use os_id and it refers to correct thread, however in other conditions it should be used only for cases when stale os_id reference is harmless, like logging.

I have tried to reword this section to better communicate this, thank. Let me know if you see any better way to put this into words.

///
/// # Examples
///
/// ```
/// #![feature(thread_os_id)]
/// use std::thread;
///
/// let spawned = thread::spawn(|| thread::current().os_id());
/// println!("spawned thread ran as {:?}", spawned.join().unwrap());

@tgross35 tgross35 Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could this do the assert_ne! test here? I think that demos relevant properties a bit better.

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, applied the changes but guarded it so it will not fail on other platforms that do not support os_id and could return None making it fail.

/// ```
#[unstable(feature = "thread_os_id", issue = "160215")]
#[must_use]
pub fn os_id(&self) -> Option<u64> {
self.inner.os_id.get()
}

/// Gets the thread's name.
///
/// For more information about named threads, see
Expand Down
Loading