@@ -165,6 +165,7 @@ use panic;
165
165
use panicking;
166
166
use str;
167
167
use sync:: { Mutex , Condvar , Arc } ;
168
+ use sync:: atomic:: { AtomicUsize , Ordering , ATOMIC_USIZE_INIT } ;
168
169
use sys:: thread as imp;
169
170
use sys_common:: thread_info;
170
171
use sys_common:: util;
@@ -524,6 +525,35 @@ pub fn park_timeout(dur: Duration) {
524
525
* guard = false ;
525
526
}
526
527
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
+
527
557
////////////////////////////////////////////////////////////////////////////////
528
558
// Thread
529
559
////////////////////////////////////////////////////////////////////////////////
@@ -977,6 +1007,16 @@ mod tests {
977
1007
thread:: sleep ( Duration :: from_millis ( 2 ) ) ;
978
1008
}
979
1009
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
+
980
1020
// NOTE: the corresponding test for stderr is in run-pass/thread-stderr, due
981
1021
// to the test harness apparently interfering with stderr configuration.
982
1022
}
0 commit comments