about summary refs log tree commit diff
path: root/src/libstd/thread
diff options
context:
space:
mode:
authorStephen M. Coakley <me@stephencoakley.com>2016-09-07 23:48:07 -0500
committerStephen M. Coakley <me@stephencoakley.com>2016-09-07 23:48:07 -0500
commit5bd834bdb4e2c1fe6666be8c8fad41526d72e3d1 (patch)
tree178d4010b384a492b4d0417be1d736b70b410a2c /src/libstd/thread
parent9627e9ef6e0183e50b6a985143d31d82bda31cfe (diff)
downloadrust-5bd834bdb4e2c1fe6666be8c8fad41526d72e3d1.tar.gz
rust-5bd834bdb4e2c1fe6666be8c8fad41526d72e3d1.zip
Add ThreadId for comparing threads
Diffstat (limited to 'src/libstd/thread')
-rw-r--r--src/libstd/thread/mod.rs40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs
index d8e021bb04f..97a277e7bb4 100644
--- a/src/libstd/thread/mod.rs
+++ b/src/libstd/thread/mod.rs
@@ -165,6 +165,7 @@ use panic;
 use panicking;
 use str;
 use sync::{Mutex, Condvar, Arc};
+use sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
 use sys::thread as imp;
 use sys_common::thread_info;
 use sys_common::util;
@@ -525,6 +526,35 @@ pub fn park_timeout(dur: Duration) {
 }
 
 ////////////////////////////////////////////////////////////////////////////////
+// ThreadId
+////////////////////////////////////////////////////////////////////////////////
+
+/// A unique identifier for a running thread.
+///
+/// A `ThreadId` is an opaque object that has a unique value for each thread
+/// that creates one. `ThreadId`s do not correspond to a thread's system-
+/// designated identifier.
+#[unstable(feature = "thread_id", issue = "21507")]
+#[derive(Eq, PartialEq, Copy, Clone)]
+pub struct ThreadId(usize);
+
+impl ThreadId {
+    /// Returns an identifier unique to the current calling thread.
+    #[unstable(feature = "thread_id", issue = "21507")]
+    pub fn current() -> ThreadId {
+        static THREAD_ID_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
+        #[thread_local] static mut THREAD_ID: ThreadId = ThreadId(0);
+
+        unsafe {
+            if THREAD_ID.0 == 0 {
+                THREAD_ID.0 = 1 + THREAD_ID_COUNT.fetch_add(1, Ordering::SeqCst);
+            }
+            THREAD_ID
+        }
+    }
+}
+
+////////////////////////////////////////////////////////////////////////////////
 // Thread
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -977,6 +1007,16 @@ mod tests {
         thread::sleep(Duration::from_millis(2));
     }
 
+    #[test]
+    fn test_thread_id_equal() {
+        assert_eq!(ThreadId::current(), ThreadId::current());
+    }
+
+    #[test]
+    fn test_thread_id_not_equal() {
+        assert!(ThreadId::current() != spawn(|| ThreadId::current()).join());
+    }
+
     // NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
     // to the test harness apparently interfering with stderr configuration.
 }