std/thread/thread.rs
1use super::id::ThreadId;
2use super::main_thread;
3use crate::alloc::System;
4use crate::ffi::CStr;
5use crate::fmt;
6use crate::pin::Pin;
7use crate::sync::{Arc, OnceLock};
8use crate::sys::sync::Parker;
9use crate::sys::thread as imp;
10use crate::time::Duration;
11
12// This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
13mod thread_name_string {
14 use crate::ffi::{CStr, CString};
15 use crate::str;
16
17 /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
18 pub(crate) struct ThreadNameString {
19 inner: CString,
20 }
21
22 impl From<String> for ThreadNameString {
23 #[ferrocene::prevalidated]
24 fn from(s: String) -> Self {
25 Self {
26 inner: CString::new(s).expect("thread name may not contain interior null bytes"),
27 }
28 }
29 }
30
31 impl ThreadNameString {
32 pub(crate) fn as_cstr(&self) -> &CStr {
33 &self.inner
34 }
35
36 pub(crate) fn as_str(&self) -> &str {
37 // SAFETY: `ThreadNameString` is guaranteed to be UTF-8.
38 unsafe { str::from_utf8_unchecked(self.inner.to_bytes()) }
39 }
40 }
41}
42
43use thread_name_string::ThreadNameString;
44
45/// The internal representation of a `Thread` handle
46///
47/// We explicitly set the alignment for our guarantee in Thread::into_raw. This
48/// allows applications to stuff extra metadata bits into the alignment, which
49/// can be rather useful when working with atomics.
50#[repr(align(8))]
51struct Inner {
52 name: Option<ThreadNameString>,
53 id: ThreadId,
54 os_id: OnceLock<u64>,
55 parker: Parker,
56}
57
58impl Inner {
59 #[ferrocene::prevalidated]
60 fn parker(self: Pin<&Self>) -> Pin<&Parker> {
61 unsafe { Pin::map_unchecked(self, |inner| &inner.parker) }
62 }
63}
64
65#[ferrocene::prevalidated]
66#[allow(ferrocene::unvalidated, reason = "false-positive in derived Clone implementation")]
67#[derive(Clone)]
68#[stable(feature = "rust1", since = "1.0.0")]
69/// A handle to a thread.
70///
71/// Threads are represented via the `Thread` type, which you can get in one of
72/// two ways:
73///
74/// * By spawning a new thread, e.g., using the [`thread::spawn`]
75/// function, and calling [`thread`] on the [`JoinHandle`].
76/// * By requesting the current thread, using the [`thread::current`] function.
77///
78/// The [`thread::current`] function is available even for threads not spawned
79/// by the APIs of this module.
80///
81/// There is usually no need to create a `Thread` struct yourself, one
82/// should instead use a function like `spawn` to create new threads, see the
83/// docs of [`Builder`] and [`spawn`] for more details.
84///
85/// [`thread::spawn`]: super::spawn
86/// [`thread`]: super::JoinHandle::thread
87/// [`JoinHandle`]: super::JoinHandle
88/// [`thread::current`]: super::current::current
89/// [`Builder`]: super::Builder
90/// [`spawn`]: super::spawn
91pub struct Thread {
92 // We use the System allocator such that creating or dropping this handle
93 // does not interfere with a potential Global allocator using thread-local
94 // storage.
95 inner: Pin<Arc<Inner, System>>,
96}
97
98impl Thread {
99 #[ferrocene::prevalidated]
100 pub(crate) fn new(id: ThreadId, name: Option<String>) -> Thread {
101 // Ferrocene modification: Don't call `.map` but `match` to work around
102 // `ferrocene::unvalidated` bug.
103 // let name = name.map(ThreadNameString::from);
104 let name = match name {
105 Some(name) => Some(ThreadNameString::from(name)),
106 None => None,
107 };
108
109 // We have to use `unsafe` here to construct the `Parker` in-place,
110 // which is required for the UNIX implementation.
111 //
112 // SAFETY: We pin the Arc immediately after creation, so its address never
113 // changes.
114 let inner = unsafe {
115 let mut arc = Arc::<Inner, _>::new_uninit_in(System);
116 let ptr = Arc::get_mut_unchecked(&mut arc).as_mut_ptr();
117 (&raw mut (*ptr).name).write(name);
118 (&raw mut (*ptr).id).write(id);
119 (&raw mut (*ptr).os_id).write(OnceLock::new());
120 #[expect(ferrocene::unvalidated, reason = "defer validating platform specifics")]
121 Parker::new_in_place(&raw mut (*ptr).parker);
122 Pin::new_unchecked(arc.assume_init())
123 };
124
125 Thread { inner }
126 }
127
128 /// Creates a handle for the calling thread, recording its OS id.
129 ///
130 /// `id` must be the `ThreadId` of the calling thread.
131 ///
132 /// Takes no name because passing one into `Thread::new` allocates with the
133 /// global allocator, which `thread::current` is documented never to use.
134 pub(crate) fn new_current(id: ThreadId) -> Thread {
135 let thread = Thread::new(id, None);
136 thread.set_os_id_to_current();
137 thread
138 }
139
140 /// Records the calling thread's OS id, as reported by
141 /// `imp::current_os_id`, in this handle.
142 ///
143 /// May only be called from the thread to which this handle belongs. A
144 /// spawned thread does this itself once it starts running, since its handle
145 /// already exists by then.
146 ///
147 /// `imp::current_os_id` must not allocate with the global allocator or call
148 /// `thread::current`.
149 pub(crate) fn set_os_id_to_current(&self) {
150 if let Some(os_id) = imp::current_os_id() {
151 if self.inner.os_id.set(os_id).is_err() {
152 rtabort!("thread OS id already set");
153 }
154 }
155 }
156
157 /// Like the public [`park`], but callable on any handle. This is used to
158 /// allow parking in TLS destructors.
159 ///
160 /// # Safety
161 /// May only be called from the thread to which this handle belongs.
162 ///
163 /// [`park`]: super::park
164 pub(crate) unsafe fn park(&self) {
165 unsafe { self.inner.as_ref().parker().park() }
166 }
167
168 /// Like the public [`park_timeout`], but callable on any handle. This is
169 /// used to allow parking in TLS destructors.
170 ///
171 /// # Safety
172 /// May only be called from the thread to which this handle belongs.
173 ///
174 /// [`park_timeout`]: super::park_timeout
175 pub(crate) unsafe fn park_timeout(&self, dur: Duration) {
176 unsafe { self.inner.as_ref().parker().park_timeout(dur) }
177 }
178
179 /// Atomically makes the handle's token available if it is not already.
180 ///
181 /// Every thread is equipped with some basic low-level blocking support, via
182 /// the [`park`] function and the `unpark()` method. These can be used as a
183 /// more CPU-efficient implementation of a spinlock.
184 ///
185 /// See the [park documentation] for more details.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// use std::thread;
191 /// use std::time::Duration;
192 /// use std::sync::atomic::{AtomicBool, Ordering};
193 ///
194 /// static QUEUED: AtomicBool = AtomicBool::new(false);
195 ///
196 /// let parked_thread = thread::Builder::new()
197 /// .spawn(|| {
198 /// println!("Parking thread");
199 /// QUEUED.store(true, Ordering::Release);
200 /// thread::park();
201 /// println!("Thread unparked");
202 /// })
203 /// .unwrap();
204 ///
205 /// // Let some time pass for the thread to be spawned.
206 /// thread::sleep(Duration::from_millis(10));
207 ///
208 /// // Wait until the other thread is queued.
209 /// // This is crucial! It guarantees that the `unpark` below is not consumed
210 /// // by some other code in the parked thread (e.g. inside `println!`).
211 /// while !QUEUED.load(Ordering::Acquire) {
212 /// // Spinning is of course inefficient; in practice, this would more likely be
213 /// // a dequeue where we have no work to do if there's nobody queued.
214 /// std::hint::spin_loop();
215 /// }
216 ///
217 /// println!("Unpark the thread");
218 /// parked_thread.thread().unpark();
219 ///
220 /// parked_thread.join().unwrap();
221 /// ```
222 ///
223 /// [`park`]: super::park
224 /// [park documentation]: super::park
225 #[ferrocene::prevalidated]
226 #[stable(feature = "rust1", since = "1.0.0")]
227 #[inline]
228 pub fn unpark(&self) {
229 // Ferrocene modification: Split `unpark` call apart in order to skip
230 // it from validation.
231 let parker = self.inner.as_ref().parker();
232 #[expect(ferrocene::unvalidated, reason = "defer validating platform specifics")]
233 parker.unpark();
234 }
235
236 /// Gets the thread's unique identifier.
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// use std::thread;
242 ///
243 /// let other_thread = thread::spawn(|| {
244 /// thread::current().id()
245 /// });
246 ///
247 /// let other_thread_id = other_thread.join().unwrap();
248 /// assert!(thread::current().id() != other_thread_id);
249 /// ```
250 #[stable(feature = "thread_id", since = "1.19.0")]
251 #[must_use]
252 pub fn id(&self) -> ThreadId {
253 self.inner.id
254 }
255
256 /// Gets the id the operating system gave this thread, if it has one that can
257 /// be read.
258 ///
259 /// This is the id that shows up in tools like `ps` and `top`, debuggers and
260 /// crash logs, unlike [`ThreadId`], which has no guaranteed relationship to
261 /// it. On a platform with no OS-visible thread id, such as SGX, the value
262 /// may be some other per-thread value (there, the thread's address), which
263 /// such tools will not recognize. `None` means no id could be recorded: the
264 /// thread has not started running yet, or the platform has no way to read
265 /// one.
266 ///
267 /// The operating system may reuse the id of a thread that has exited, and a
268 /// `Thread` handle can outlive the thread it refers to. After a `fork`, the
269 /// id recorded in the child process still refers to the parent's thread; it
270 /// is not re-read. Use the id only where a reused or stale id is harmless,
271 /// such as logging.
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// #![feature(thread_os_id)]
277 /// use std::thread;
278 ///
279 /// let spawned = thread::spawn(|| thread::current().os_id()).join().unwrap();
280 /// if spawned.is_some() {
281 /// assert_ne!(spawned, thread::current().os_id());
282 /// }
283 /// ```
284 #[unstable(feature = "thread_os_id", issue = "160215")]
285 #[must_use]
286 pub fn os_id(&self) -> Option<u64> {
287 self.inner.os_id.get().copied()
288 }
289
290 /// Gets the thread's name.
291 ///
292 /// For more information about named threads, see
293 /// [this module-level documentation][naming-threads].
294 ///
295 /// # Examples
296 ///
297 /// Threads by default have no name specified:
298 ///
299 /// ```
300 /// use std::thread;
301 ///
302 /// let builder = thread::Builder::new();
303 ///
304 /// let handler = builder.spawn(|| {
305 /// assert!(thread::current().name().is_none());
306 /// }).unwrap();
307 ///
308 /// handler.join().unwrap();
309 /// ```
310 ///
311 /// Thread with a specified name:
312 ///
313 /// ```
314 /// use std::thread;
315 ///
316 /// let builder = thread::Builder::new()
317 /// .name("foo".into());
318 ///
319 /// let handler = builder.spawn(|| {
320 /// assert_eq!(thread::current().name(), Some("foo"))
321 /// }).unwrap();
322 ///
323 /// handler.join().unwrap();
324 /// ```
325 ///
326 /// [naming-threads]: ./index.html#naming-threads
327 #[stable(feature = "rust1", since = "1.0.0")]
328 #[must_use]
329 pub fn name(&self) -> Option<&str> {
330 if let Some(name) = &self.inner.name {
331 Some(name.as_str())
332 } else if main_thread::get() == Some(self.inner.id) {
333 Some("main")
334 } else {
335 None
336 }
337 }
338
339 /// Consumes the `Thread`, returning a raw pointer.
340 ///
341 /// To avoid a memory leak the pointer must be converted
342 /// back into a `Thread` using [`Thread::from_raw`]. The pointer is
343 /// guaranteed to be aligned to at least 8 bytes.
344 ///
345 /// # Examples
346 ///
347 /// ```
348 /// #![feature(thread_raw)]
349 ///
350 /// use std::thread::{self, Thread};
351 ///
352 /// let thread = thread::current();
353 /// let id = thread.id();
354 /// let ptr = Thread::into_raw(thread);
355 /// unsafe {
356 /// assert_eq!(Thread::from_raw(ptr).id(), id);
357 /// }
358 /// ```
359 #[unstable(feature = "thread_raw", issue = "97523")]
360 pub fn into_raw(self) -> *const () {
361 // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant.
362 let inner = unsafe { Pin::into_inner_unchecked(self.inner) };
363 Arc::into_raw_with_allocator(inner).0 as *const ()
364 }
365
366 /// Constructs a `Thread` from a raw pointer.
367 ///
368 /// The raw pointer must have been previously returned
369 /// by a call to [`Thread::into_raw`].
370 ///
371 /// # Safety
372 ///
373 /// This function is unsafe because improper use may lead
374 /// to memory unsafety, even if the returned `Thread` is never
375 /// accessed.
376 ///
377 /// Creating a `Thread` from a pointer other than one returned
378 /// from [`Thread::into_raw`] is **undefined behavior**.
379 ///
380 /// Calling this function twice on the same raw pointer can lead
381 /// to a double-free if both `Thread` instances are dropped.
382 #[unstable(feature = "thread_raw", issue = "97523")]
383 pub unsafe fn from_raw(ptr: *const ()) -> Thread {
384 // Safety: Upheld by caller.
385 unsafe {
386 Thread { inner: Pin::new_unchecked(Arc::from_raw_in(ptr as *const Inner, System)) }
387 }
388 }
389
390 pub(crate) fn cname(&self) -> Option<&CStr> {
391 if let Some(name) = &self.inner.name {
392 Some(name.as_cstr())
393 } else if main_thread::get() == Some(self.inner.id) {
394 Some(c"main")
395 } else {
396 None
397 }
398 }
399}
400
401#[stable(feature = "rust1", since = "1.0.0")]
402impl fmt::Debug for Thread {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.debug_struct("Thread")
405 .field("id", &self.id())
406 .field("name", &self.name())
407 .finish_non_exhaustive()
408 }
409}