@@ -165,8 +165,8 @@ use panic;
165
165
use panicking;
166
166
use str;
167
167
use sync:: { Mutex , Condvar , Arc } ;
168
- use sync:: atomic:: { AtomicBool , Ordering } ;
169
168
use sys:: thread as imp;
169
+ use sys_common:: mutex;
170
170
use sys_common:: thread_info;
171
171
use sys_common:: util;
172
172
use sys_common:: { AsInner , IntoInner } ;
@@ -539,34 +539,14 @@ pub fn park_timeout(dur: Duration) {
539
539
pub struct ThreadId ( u64 ) ;
540
540
541
541
impl ThreadId {
542
- // Generate a new unique thread ID. Since this function is called every
543
- // time a thread is created, this is optimized to generate unique values
544
- // as quickly as possible.
542
+ // Generate a new unique thread ID.
545
543
fn new ( ) -> ThreadId {
546
- // 64-bit operations are not atomic on all systems, so use an atomic
547
- // flag as a guard around a 64-bit global counter. The window for
548
- // contention on the counter is rather narrow since the general case
549
- // should be compiled down to three instructions between locking and
550
- // unlocking the guard. Since contention on the guard is low, use a
551
- // spinlock that optimizes for the fast path of the guard being
552
- // unlocked.
553
- static GUARD : AtomicBool = AtomicBool :: new ( false ) ;
544
+ static GUARD : mutex:: Mutex = mutex:: Mutex :: new ( ) ;
554
545
static mut COUNTER : u64 = 0 ;
555
546
556
- // Get exclusive access to the counter.
557
- while GUARD . compare_exchange_weak (
558
- false ,
559
- true ,
560
- Ordering :: Acquire ,
561
- Ordering :: Relaxed
562
- ) . is_err ( ) {
563
- // Give up the rest of our thread quantum if another thread is
564
- // using the counter. This is the slow_er_ path.
565
- yield_now ( ) ;
566
- }
547
+ unsafe {
548
+ GUARD . lock ( ) ;
567
549
568
- // We have exclusive access to the counter, so use it fast and get out.
569
- let id = unsafe {
570
550
// If we somehow use up all our bits, panic so that we're not
571
551
// covering up subtle bugs of IDs being reused.
572
552
if COUNTER == :: u64:: MAX {
@@ -575,13 +555,11 @@ impl ThreadId {
575
555
576
556
let id = COUNTER ;
577
557
COUNTER += 1 ;
578
- id
579
- } ;
580
558
581
- // Unlock the guard.
582
- GUARD . store ( false , Ordering :: Release ) ;
559
+ GUARD . unlock ( ) ;
583
560
584
- ThreadId ( id)
561
+ ThreadId ( id)
562
+ }
585
563
}
586
564
}
587
565
0 commit comments