std/thread/id.rs
1use crate::num::NonZero;
2use crate::sync::atomic::{Atomic, Ordering};
3
4/// A unique identifier for a running thread.
5///
6/// A `ThreadId` is an opaque object that uniquely identifies each thread
7/// created during the lifetime of a process. `ThreadId`s are guaranteed not to
8/// be reused, even when a thread terminates. `ThreadId`s are under the control
9/// of Rust's standard library and there may not be any relationship between
10/// `ThreadId` and the underlying platform's notion of a thread identifier --
11/// the two concepts cannot, therefore, be used interchangeably. A `ThreadId`
12/// can be retrieved from the [`id`] method on a [`Thread`].
13///
14/// # Examples
15///
16/// ```
17/// use std::thread;
18///
19/// let other_thread = thread::spawn(|| {
20/// thread::current().id()
21/// });
22///
23/// let other_thread_id = other_thread.join().unwrap();
24/// assert!(thread::current().id() != other_thread_id);
25/// ```
26///
27/// [`Thread`]: super::Thread
28/// [`id`]: super::Thread::id
29#[stable(feature = "thread_id", since = "1.19.0")]
30#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
31pub struct ThreadId(NonZero<u64>);
32
33impl ThreadId {
34 // Generate a new unique thread ID.
35 #[ferrocene::prevalidated]
36 pub(crate) fn new() -> ThreadId {
37 #[cold]
38 fn exhausted() -> ! {
39 panic!("failed to generate unique thread ID: bitspace exhausted")
40 }
41
42 cfg_select! {
43 target_has_atomic = "64" => {
44 use crate::sync::atomic::AtomicU64;
45
46 static COUNTER: Atomic<u64> = AtomicU64::new(0);
47
48 let mut last = COUNTER.load(Ordering::Relaxed);
49 loop {
50 let Some(id) = last.checked_add(1) else {
51 exhausted();
52 };
53
54 match COUNTER.compare_exchange_weak(
55 last,
56 id,
57 Ordering::Relaxed,
58 Ordering::Relaxed,
59 ) {
60 Ok(_) => return ThreadId(NonZero::new(id).unwrap()),
61 Err(id) => last = id,
62 }
63 }
64 }
65 _ => {
66 use crate::cell::SyncUnsafeCell;
67 use crate::hint::spin_loop;
68 use crate::sync::atomic::AtomicBool;
69 use crate::thread::yield_now;
70
71 // If we don't have a 64-bit atomic we use a small spinlock. We don't use Mutex
72 // here as we might be trying to get the current thread id in the global allocator,
73 // and on some platforms Mutex requires allocation.
74 static COUNTER_LOCKED: Atomic<bool> = AtomicBool::new(false);
75 static COUNTER: SyncUnsafeCell<u64> = SyncUnsafeCell::new(0);
76
77 // Acquire lock.
78 let mut spin = 0;
79 // Miri doesn't like it when we yield here as it interferes with deterministically
80 // scheduling threads, so avoid `compare_exchange_weak` to avoid spurious yields.
81 while COUNTER_LOCKED.swap(true, Ordering::Acquire) {
82 if spin <= 3 {
83 for _ in 0..(1 << spin) {
84 #[allow(
85 ferrocene::unvalidated,
86 reason = "defer validating platform-specifics"
87 )]
88 spin_loop();
89 }
90 } else {
91 #[allow(
92 ferrocene::unvalidated,
93 reason = "defer validating platform-specifics"
94 )]
95 yield_now();
96 }
97 spin += 1;
98 }
99 // This was `false` before the swap, so we got the lock.
100
101 // SAFETY: we have an exclusive lock on the counter.
102 unsafe {
103 if let Some(id) = (*COUNTER.get()).checked_add(1) {
104 *COUNTER.get() = id;
105 COUNTER_LOCKED.store(false, Ordering::Release);
106 ThreadId(NonZero::new(id).unwrap())
107 } else {
108 COUNTER_LOCKED.store(false, Ordering::Release);
109 exhausted()
110 }
111 }
112 }
113 }
114 }
115
116 #[cfg(any(not(target_thread_local), target_has_atomic = "64"))]
117 pub(super) fn from_u64(v: u64) -> Option<ThreadId> {
118 NonZero::new(v).map(ThreadId)
119 }
120
121 /// This returns a numeric identifier for the thread identified by this
122 /// `ThreadId`.
123 ///
124 /// As noted in the documentation for the type itself, it is essentially an
125 /// opaque ID, but is guaranteed to be unique for each thread. The returned
126 /// value is entirely opaque -- only equality testing is stable. Note that
127 /// it is not guaranteed which values new threads will return, and this may
128 /// change across Rust versions.
129 #[must_use]
130 #[unstable(feature = "thread_id_value", issue = "67939")]
131 pub fn as_u64(&self) -> NonZero<u64> {
132 self.0
133 }
134}