@@ -519,9 +519,14 @@ impl Builder {
519
519
520
520
let f = MaybeDangling :: new ( f) ;
521
521
let main = move || {
522
- // Immediately store the thread handle to avoid setting it or its ID
523
- // twice, which would cause an abort.
524
- set_current ( their_thread. clone ( ) ) ;
522
+ if let Err ( _thread) = set_current ( their_thread. clone ( ) ) {
523
+ // Both the current thread handle and the ID should not be
524
+ // initialized yet. Since only the C runtime and some of our
525
+ // platform code run before this, this point shouldn't be
526
+ // reachable. Use an abort to save binary size (see #123356).
527
+ rtabort ! ( "something here is badly broken!" ) ;
528
+ }
529
+
525
530
if let Some ( name) = their_thread. cname ( ) {
526
531
imp:: Thread :: set_name ( name) ;
527
532
}
@@ -1159,9 +1164,6 @@ pub fn park_timeout(dur: Duration) {
1159
1164
pub struct ThreadId ( NonZero < u64 > ) ;
1160
1165
1161
1166
impl ThreadId {
1162
- // DO NOT rely on this value.
1163
- const MAIN_THREAD : ThreadId = ThreadId ( unsafe { NonZero :: new_unchecked ( 1 ) } ) ;
1164
-
1165
1167
// Generate a new unique thread ID.
1166
1168
pub ( crate ) fn new ( ) -> ThreadId {
1167
1169
#[ cold]
@@ -1173,7 +1175,7 @@ impl ThreadId {
1173
1175
if #[ cfg( target_has_atomic = "64" ) ] {
1174
1176
use crate :: sync:: atomic:: AtomicU64 ;
1175
1177
1176
- static COUNTER : AtomicU64 = AtomicU64 :: new( 1 ) ;
1178
+ static COUNTER : AtomicU64 = AtomicU64 :: new( 0 ) ;
1177
1179
1178
1180
let mut last = COUNTER . load( Ordering :: Relaxed ) ;
1179
1181
loop {
@@ -1189,7 +1191,7 @@ impl ThreadId {
1189
1191
} else {
1190
1192
use crate :: sync:: { Mutex , PoisonError } ;
1191
1193
1192
- static COUNTER : Mutex <u64 > = Mutex :: new( 1 ) ;
1194
+ static COUNTER : Mutex <u64 > = Mutex :: new( 0 ) ;
1193
1195
1194
1196
let mut counter = COUNTER . lock( ) . unwrap_or_else( PoisonError :: into_inner) ;
1195
1197
let Some ( id) = counter. checked_add( 1 ) else {
@@ -1326,9 +1328,9 @@ impl Thread {
1326
1328
Self :: new_inner ( id, ThreadName :: Unnamed )
1327
1329
}
1328
1330
1329
- // Used in runtime to construct main thread
1330
- pub ( crate ) fn new_main ( ) -> Thread {
1331
- Self :: new_inner ( ThreadId :: MAIN_THREAD , ThreadName :: Main )
1331
+ /// Constructs the thread handle for the main thread.
1332
+ pub ( crate ) fn new_main ( id : ThreadId ) -> Thread {
1333
+ Self :: new_inner ( id , ThreadName :: Main )
1332
1334
}
1333
1335
1334
1336
fn new_inner ( id : ThreadId , name : ThreadName ) -> Thread {
0 commit comments