Skip to content

Commit 5bd834b

Browse files
committed
Add ThreadId for comparing threads
1 parent 9627e9e commit 5bd834b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/libstd/thread/mod.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ use panic;
165165
use panicking;
166166
use str;
167167
use sync::{Mutex, Condvar, Arc};
168+
use sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
168169
use sys::thread as imp;
169170
use sys_common::thread_info;
170171
use sys_common::util;
@@ -524,6 +525,35 @@ pub fn park_timeout(dur: Duration) {
524525
*guard = false;
525526
}
526527

528+
////////////////////////////////////////////////////////////////////////////////
529+
// ThreadId
530+
////////////////////////////////////////////////////////////////////////////////
531+
532+
/// A unique identifier for a running thread.
533+
///
534+
/// A `ThreadId` is an opaque object that has a unique value for each thread
535+
/// that creates one. `ThreadId`s do not correspond to a thread's system-
536+
/// designated identifier.
537+
#[unstable(feature = "thread_id", issue = "21507")]
538+
#[derive(Eq, PartialEq, Copy, Clone)]
539+
pub struct ThreadId(usize);
540+
541+
impl ThreadId {
542+
/// Returns an identifier unique to the current calling thread.
543+
#[unstable(feature = "thread_id", issue = "21507")]
544+
pub fn current() -> ThreadId {
545+
static THREAD_ID_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
546+
#[thread_local] static mut THREAD_ID: ThreadId = ThreadId(0);
547+
548+
unsafe {
549+
if THREAD_ID.0 == 0 {
550+
THREAD_ID.0 = 1 + THREAD_ID_COUNT.fetch_add(1, Ordering::SeqCst);
551+
}
552+
THREAD_ID
553+
}
554+
}
555+
}
556+
527557
////////////////////////////////////////////////////////////////////////////////
528558
// Thread
529559
////////////////////////////////////////////////////////////////////////////////
@@ -977,6 +1007,16 @@ mod tests {
9771007
thread::sleep(Duration::from_millis(2));
9781008
}
9791009

1010+
#[test]
1011+
fn test_thread_id_equal() {
1012+
assert_eq!(ThreadId::current(), ThreadId::current());
1013+
}
1014+
1015+
#[test]
1016+
fn test_thread_id_not_equal() {
1017+
assert!(ThreadId::current() != spawn(|| ThreadId::current()).join());
1018+
}
1019+
9801020
// NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
9811021
// to the test harness apparently interfering with stderr configuration.
9821022
}

0 commit comments

Comments
 (0)