159159mod tests;
160160
161161use crate :: any:: Any ;
162+ use crate :: cell:: SyncUnsafeCell ;
162163use crate :: cell:: { OnceCell , UnsafeCell } ;
163164use crate :: env;
164165use crate :: ffi:: { CStr , CString } ;
165166use crate :: fmt;
166167use crate :: io;
167168use crate :: marker:: PhantomData ;
169+ use crate :: mem:: MaybeUninit ;
168170use crate :: mem:: { self , forget} ;
169171use crate :: num:: NonZero ;
170172use crate :: panic;
@@ -530,7 +532,7 @@ impl Builder {
530532
531533 let f = MaybeDangling :: new ( f) ;
532534 let main = move || {
533- if let Some ( name) = their_thread. cname ( ) {
535+ if let Some ( name) = their_thread. 0 . name ( ) {
534536 imp:: Thread :: set_name ( name) ;
535537 }
536538
@@ -1162,7 +1164,7 @@ pub fn park_timeout(dur: Duration) {
11621164 let guard = PanicGuard ;
11631165 // SAFETY: park_timeout is called on the parker owned by this thread.
11641166 unsafe {
1165- current ( ) . inner . as_ref ( ) . parker ( ) . park_timeout ( dur) ;
1167+ current ( ) . 0 . parker ( ) . park_timeout ( dur) ;
11661168 }
11671169 // No panic occurred, do not abort.
11681170 forget ( guard) ;
@@ -1201,7 +1203,12 @@ pub fn park_timeout(dur: Duration) {
12011203pub struct ThreadId ( NonZero < u64 > ) ;
12021204
12031205impl ThreadId {
1204- // Generate a new unique thread ID.
1206+ /// Generate a new unique thread ID.
1207+ ///
1208+ /// The current implementation starts at 2 and increments from there.
1209+ ///
1210+ /// This is as `1` is the value for the main thread, so std::thread::Thread does not
1211+ /// have to store this value when creating the main thread's information.
12051212 fn new ( ) -> ThreadId {
12061213 #[ cold]
12071214 fn exhausted ( ) -> ! {
@@ -1212,7 +1219,7 @@ impl ThreadId {
12121219 if #[ cfg( target_has_atomic = "64" ) ] {
12131220 use crate :: sync:: atomic:: AtomicU64 ;
12141221
1215- static COUNTER : AtomicU64 = AtomicU64 :: new( 0 ) ;
1222+ static COUNTER : AtomicU64 = AtomicU64 :: new( 1 ) ;
12161223
12171224 let mut last = COUNTER . load( Ordering :: Relaxed ) ;
12181225 loop {
@@ -1228,7 +1235,7 @@ impl ThreadId {
12281235 } else {
12291236 use crate :: sync:: { Mutex , PoisonError } ;
12301237
1231- static COUNTER : Mutex <u64 > = Mutex :: new( 0 ) ;
1238+ static COUNTER : Mutex <u64 > = Mutex :: new( 1 ) ;
12321239
12331240 let mut counter = COUNTER . lock( ) . unwrap_or_else( PoisonError :: into_inner) ;
12341241 let Some ( id) = counter. checked_add( 1 ) else {
@@ -1245,6 +1252,11 @@ impl ThreadId {
12451252 }
12461253 }
12471254
1255+ /// Creates a ThreadId with the ID of the main thread.
1256+ fn new_main ( ) -> Self {
1257+ Self ( NonZero :: < u64 > :: MIN )
1258+ }
1259+
12481260 /// This returns a numeric identifier for the thread identified by this
12491261 /// `ThreadId`.
12501262 ///
@@ -1264,23 +1276,54 @@ impl ThreadId {
12641276// Thread
12651277////////////////////////////////////////////////////////////////////////////////
12661278
1267- /// The internal representation of a `Thread`'s name.
1268- enum ThreadName {
1269- Main ,
1270- Other ( CString ) ,
1271- Unnamed ,
1272- }
1279+ /// The parker for the main thread. This avoids having to allocate an Arc in `fn main() {}`.
1280+ static MAIN_PARKER : SyncUnsafeCell < MaybeUninit < Parker > > =
1281+ SyncUnsafeCell :: new ( MaybeUninit :: uninit ( ) ) ;
12731282
1274- /// The internal representation of a `Thread` handle
1275- struct Inner {
1276- name : ThreadName , // Guaranteed to be UTF-8
1283+ /// The internal representation of a `Thread` that is not the main thread.
1284+ struct OtherInner {
1285+ name : Option < CString > , // Guaranteed to be UTF-8
12771286 id : ThreadId ,
12781287 parker : Parker ,
12791288}
12801289
1290+ /// The internal representation of a `Thread` handle.
1291+ #[ derive( Clone ) ]
1292+ enum Inner {
1293+ Main ,
1294+ Other ( Pin < Arc < OtherInner > > ) ,
1295+ }
1296+
12811297impl Inner {
1282- fn parker ( self : Pin < & Self > ) -> Pin < & Parker > {
1283- unsafe { Pin :: map_unchecked ( self , |inner| & inner. parker ) }
1298+ fn id ( & self ) -> ThreadId {
1299+ match self {
1300+ Self :: Main => ThreadId :: new_main ( ) ,
1301+ Self :: Other ( other) => other. id ,
1302+ }
1303+ }
1304+
1305+ fn name ( & self ) -> Option < & CStr > {
1306+ match self {
1307+ Self :: Main => Some ( c"main" ) ,
1308+ Self :: Other ( other) => other. name . as_deref ( ) ,
1309+ }
1310+ }
1311+
1312+ fn parker ( & self ) -> Pin < & Parker > {
1313+ match self {
1314+ Self :: Main => {
1315+ // Safety: MAIN_PARKER only ever has a mutable reference when Inner::Main is initialised.
1316+ let static_ref: & ' static MaybeUninit < Parker > = unsafe { & * MAIN_PARKER . get ( ) } ;
1317+
1318+ // Safety: MAIN_PARKER is initialised when Inner::Main is initialised.
1319+ let parker_ref = unsafe { static_ref. assume_init_ref ( ) } ;
1320+
1321+ Pin :: static_ref ( parker_ref)
1322+ }
1323+ Self :: Other ( inner) => unsafe {
1324+ Pin :: map_unchecked ( inner. as_ref ( ) , |inner| & inner. parker )
1325+ } ,
1326+ }
12841327 }
12851328}
12861329
@@ -1304,46 +1347,53 @@ impl Inner {
13041347/// docs of [`Builder`] and [`spawn`] for more details.
13051348///
13061349/// [`thread::current`]: current
1307- pub struct Thread {
1308- inner : Pin < Arc < Inner > > ,
1309- }
1350+ pub struct Thread ( Inner ) ;
13101351
13111352impl Thread {
13121353 /// Used only internally to construct a thread object without spawning.
13131354 ///
13141355 /// # Safety
13151356 /// `name` must be valid UTF-8.
13161357 pub ( crate ) unsafe fn new ( name : CString ) -> Thread {
1317- unsafe { Self :: new_inner ( ThreadName :: Other ( name) ) }
1358+ unsafe { Self :: new_inner ( Some ( name) ) }
13181359 }
13191360
13201361 pub ( crate ) fn new_unnamed ( ) -> Thread {
1321- unsafe { Self :: new_inner ( ThreadName :: Unnamed ) }
1362+ unsafe { Self :: new_inner ( None ) }
13221363 }
13231364
1324- // Used in runtime to construct main thread
1325- pub ( crate ) fn new_main ( ) -> Thread {
1326- unsafe { Self :: new_inner ( ThreadName :: Main ) }
1365+ /// Used in runtime to construct main thread
1366+ ///
1367+ /// # Safety
1368+ ///
1369+ /// This must only ever be called once, and must be called on the main thread.
1370+ pub ( crate ) unsafe fn new_main ( ) -> Thread {
1371+ // Safety: Caller responsible for holding the mutable invariant and
1372+ // Parker::new_in_place does not read from the uninit value.
1373+ unsafe { Parker :: new_in_place ( MAIN_PARKER . get ( ) . cast ( ) ) }
1374+
1375+ Self ( Inner :: Main )
13271376 }
13281377
13291378 /// # Safety
1330- /// If `name` is `ThreadName::Other(_)`, the contained string must be valid UTF-8.
1331- unsafe fn new_inner ( name : ThreadName ) -> Thread {
1379+ ///
1380+ /// If `name` is `Some(_)`, the contained string must be valid UTF-8.
1381+ unsafe fn new_inner ( name : Option < CString > ) -> Thread {
13321382 // We have to use `unsafe` here to construct the `Parker` in-place,
13331383 // which is required for the UNIX implementation.
13341384 //
13351385 // SAFETY: We pin the Arc immediately after creation, so its address never
13361386 // changes.
13371387 let inner = unsafe {
1338- let mut arc = Arc :: < Inner > :: new_uninit ( ) ;
1388+ let mut arc = Arc :: < OtherInner > :: new_uninit ( ) ;
13391389 let ptr = Arc :: get_mut_unchecked ( & mut arc) . as_mut_ptr ( ) ;
13401390 addr_of_mut ! ( ( * ptr) . name) . write ( name) ;
13411391 addr_of_mut ! ( ( * ptr) . id) . write ( ThreadId :: new ( ) ) ;
13421392 Parker :: new_in_place ( addr_of_mut ! ( ( * ptr) . parker) ) ;
13431393 Pin :: new_unchecked ( arc. assume_init ( ) )
13441394 } ;
13451395
1346- Thread { inner }
1396+ Self ( Inner :: Other ( inner) )
13471397 }
13481398
13491399 /// Like the public [`park`], but callable on any handle. This is used to
@@ -1352,7 +1402,7 @@ impl Thread {
13521402 /// # Safety
13531403 /// May only be called from the thread to which this handle belongs.
13541404 pub ( crate ) unsafe fn park ( & self ) {
1355- unsafe { self . inner . as_ref ( ) . parker ( ) . park ( ) }
1405+ unsafe { self . 0 . parker ( ) . park ( ) }
13561406 }
13571407
13581408 /// Atomically makes the handle's token available if it is not already.
@@ -1388,7 +1438,7 @@ impl Thread {
13881438 #[ stable( feature = "rust1" , since = "1.0.0" ) ]
13891439 #[ inline]
13901440 pub fn unpark ( & self ) {
1391- self . inner . as_ref ( ) . parker ( ) . unpark ( ) ;
1441+ self . 0 . parker ( ) . unpark ( ) ;
13921442 }
13931443
13941444 /// Gets the thread's unique identifier.
@@ -1408,7 +1458,7 @@ impl Thread {
14081458 #[ stable( feature = "thread_id" , since = "1.19.0" ) ]
14091459 #[ must_use]
14101460 pub fn id ( & self ) -> ThreadId {
1411- self . inner . id
1461+ self . 0 . id ( )
14121462 }
14131463
14141464 /// Gets the thread's name.
@@ -1451,15 +1501,7 @@ impl Thread {
14511501 #[ stable( feature = "rust1" , since = "1.0.0" ) ]
14521502 #[ must_use]
14531503 pub fn name ( & self ) -> Option < & str > {
1454- self . cname ( ) . map ( |s| unsafe { str:: from_utf8_unchecked ( s. to_bytes ( ) ) } )
1455- }
1456-
1457- fn cname ( & self ) -> Option < & CStr > {
1458- match & self . inner . name {
1459- ThreadName :: Main => Some ( c"main" ) ,
1460- ThreadName :: Other ( other) => Some ( & other) ,
1461- ThreadName :: Unnamed => None ,
1462- }
1504+ self . 0 . name ( ) . map ( |s| unsafe { str:: from_utf8_unchecked ( s. to_bytes ( ) ) } )
14631505 }
14641506}
14651507
0 commit comments