Skip to content

Commit 175584f

Browse files
committed
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 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.
1 parent 3b9d04c commit 175584f

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
@@ -130,12 +130,32 @@ pub(super) fn set_current(thread: Thread) -> Result<(), Thread> {
130130
Ok(())
131131
}
132132

133-
/// Gets the id of the thread that invokes it.
133+
/// Gets the unique identifier of the thread which invokes it.
134+
///
135+
/// Calling this function may be more efficient than accessing the current
136+
/// thread id through the current thread handle. i.e. `thread::current().id()`.
134137
///
135138
/// This function will always succeed, will always return the same value for
136139
/// one thread and is guaranteed not to call the global allocator.
140+
///
141+
/// # Examples
142+
///
143+
/// ```
144+
/// #![feature(current_thread_id)]
145+
///
146+
/// use std::thread;
147+
///
148+
/// let other_thread = thread::spawn(|| {
149+
/// thread::current_id()
150+
/// });
151+
///
152+
/// let other_thread_id = other_thread.join().unwrap();
153+
/// assert!(thread::current_id() != other_thread_id);
154+
/// ```
137155
#[inline]
138-
pub(crate) fn current_id() -> ThreadId {
156+
#[must_use]
157+
#[unstable(feature = "current_thread_id", issue = "none")]
158+
pub fn current_id() -> ThreadId {
139159
// If accessing the persistent thread ID takes multiple TLS accesses, try
140160
// to retrieve it from the current thread handle, which will only take one
141161
// 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, drop_current};
186+
#[unstable(feature = "current_thread_id", issue = "none")]
187+
pub use current::current_id;
188+
pub(crate) use current::{current_or_unnamed, drop_current};
187189
use current::{set_current, try_with_current};
188190

189191
mod spawnhook;

0 commit comments

Comments
 (0)