Skip to content

Commit 3e621b3

Browse files
authored
Rollup merge of #143069 - jsimmons:current-thread-id-accessor, r=joshtriplett,tgross35
Add fast-path for accessing the current thread id Accessing the thread id is often used in profiling and debugging, as well as some approaches for sound single-threaded access to shared data. Currently the only way to access the thread id is by first obtaining a handle to the current thread. While this is not exactly slow, it does require an atomic inc-ref and dec-ref operation, as well as the injection of `Thread`'s drop code into the caller. This publicly exposes the existing fast-path for accessing the current thread id. edit: ACP: rust-lang/libs-team#650
2 parents 42d009c + cbaec31 commit 3e621b3

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

library/std/src/thread/current.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,32 @@ pub(super) fn set_current(thread: Thread) -> Result<(), Thread> {
133133
Ok(())
134134
}
135135

136-
/// Gets the id of the thread that invokes it.
136+
/// Gets the unique identifier of the thread which invokes it.
137+
///
138+
/// Calling this function may be more efficient than accessing the current
139+
/// thread id through the current thread handle. i.e. `thread::current().id()`.
137140
///
138141
/// This function will always succeed, will always return the same value for
139142
/// one thread and is guaranteed not to call the global allocator.
143+
///
144+
/// # Examples
145+
///
146+
/// ```
147+
/// #![feature(current_thread_id)]
148+
///
149+
/// use std::thread;
150+
///
151+
/// let other_thread = thread::spawn(|| {
152+
/// thread::current_id()
153+
/// });
154+
///
155+
/// let other_thread_id = other_thread.join().unwrap();
156+
/// assert_ne!(thread::current_id(), other_thread_id);
157+
/// ```
140158
#[inline]
141-
pub(crate) fn current_id() -> ThreadId {
159+
#[must_use]
160+
#[unstable(feature = "current_thread_id", issue = "147194")]
161+
pub fn current_id() -> ThreadId {
142162
// If accessing the persistent thread ID takes multiple TLS accesses, try
143163
// to retrieve it from the current thread handle, which will only take one
144164
// TLS access.

library/std/src/thread/mod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,9 @@ mod current;
183183

184184
#[stable(feature = "rust1", since = "1.0.0")]
185185
pub use current::current;
186-
pub(crate) use current::{current_id, current_or_unnamed, current_os_id, drop_current};
186+
#[unstable(feature = "current_thread_id", issue = "147194")]
187+
pub use current::current_id;
188+
pub(crate) use current::{current_or_unnamed, current_os_id, drop_current};
187189
use current::{set_current, try_with_current};
188190

189191
mod spawnhook;

0 commit comments

Comments
 (0)