159
159
mod tests;
160
160
161
161
use crate :: any:: Any ;
162
+ use crate :: cell:: SyncUnsafeCell ;
162
163
use crate :: cell:: { OnceCell , UnsafeCell } ;
163
164
use crate :: env;
164
165
use crate :: ffi:: { CStr , CString } ;
165
166
use crate :: fmt;
166
167
use crate :: io;
167
168
use crate :: marker:: PhantomData ;
169
+ use crate :: mem:: MaybeUninit ;
168
170
use crate :: mem:: { self , forget} ;
169
171
use crate :: num:: NonZero ;
170
172
use crate :: panic;
@@ -530,7 +532,7 @@ impl Builder {
530
532
531
533
let f = MaybeDangling :: new ( f) ;
532
534
let main = move || {
533
- if let Some ( name) = their_thread. cname ( ) {
535
+ if let Some ( name) = their_thread. 0 . name ( ) {
534
536
imp:: Thread :: set_name ( name) ;
535
537
}
536
538
@@ -1162,7 +1164,7 @@ pub fn park_timeout(dur: Duration) {
1162
1164
let guard = PanicGuard ;
1163
1165
// SAFETY: park_timeout is called on the parker owned by this thread.
1164
1166
unsafe {
1165
- current ( ) . inner . as_ref ( ) . parker ( ) . park_timeout ( dur) ;
1167
+ current ( ) . 0 . parker ( ) . park_timeout ( dur) ;
1166
1168
}
1167
1169
// No panic occurred, do not abort.
1168
1170
forget ( guard) ;
@@ -1201,7 +1203,12 @@ pub fn park_timeout(dur: Duration) {
1201
1203
pub struct ThreadId ( NonZero < u64 > ) ;
1202
1204
1203
1205
impl 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.
1205
1212
fn new ( ) -> ThreadId {
1206
1213
#[ cold]
1207
1214
fn exhausted ( ) -> ! {
@@ -1212,7 +1219,7 @@ impl ThreadId {
1212
1219
if #[ cfg( target_has_atomic = "64" ) ] {
1213
1220
use crate :: sync:: atomic:: AtomicU64 ;
1214
1221
1215
- static COUNTER : AtomicU64 = AtomicU64 :: new( 0 ) ;
1222
+ static COUNTER : AtomicU64 = AtomicU64 :: new( 1 ) ;
1216
1223
1217
1224
let mut last = COUNTER . load( Ordering :: Relaxed ) ;
1218
1225
loop {
@@ -1228,7 +1235,7 @@ impl ThreadId {
1228
1235
} else {
1229
1236
use crate :: sync:: { Mutex , PoisonError } ;
1230
1237
1231
- static COUNTER : Mutex <u64 > = Mutex :: new( 0 ) ;
1238
+ static COUNTER : Mutex <u64 > = Mutex :: new( 1 ) ;
1232
1239
1233
1240
let mut counter = COUNTER . lock( ) . unwrap_or_else( PoisonError :: into_inner) ;
1234
1241
let Some ( id) = counter. checked_add( 1 ) else {
@@ -1245,6 +1252,11 @@ impl ThreadId {
1245
1252
}
1246
1253
}
1247
1254
1255
+ /// Creates a ThreadId with the ID of the main thread.
1256
+ fn new_main ( ) -> Self {
1257
+ Self ( NonZero :: < u64 > :: MIN )
1258
+ }
1259
+
1248
1260
/// This returns a numeric identifier for the thread identified by this
1249
1261
/// `ThreadId`.
1250
1262
///
@@ -1264,23 +1276,54 @@ impl ThreadId {
1264
1276
// Thread
1265
1277
////////////////////////////////////////////////////////////////////////////////
1266
1278
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 ( ) ) ;
1273
1282
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
1277
1286
id : ThreadId ,
1278
1287
parker : Parker ,
1279
1288
}
1280
1289
1290
+ /// The internal representation of a `Thread` handle.
1291
+ #[ derive( Clone ) ]
1292
+ enum Inner {
1293
+ Main ,
1294
+ Other ( Pin < Arc < OtherInner > > ) ,
1295
+ }
1296
+
1281
1297
impl 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
+ }
1284
1327
}
1285
1328
}
1286
1329
@@ -1304,46 +1347,53 @@ impl Inner {
1304
1347
/// docs of [`Builder`] and [`spawn`] for more details.
1305
1348
///
1306
1349
/// [`thread::current`]: current
1307
- pub struct Thread {
1308
- inner : Pin < Arc < Inner > > ,
1309
- }
1350
+ pub struct Thread ( Inner ) ;
1310
1351
1311
1352
impl Thread {
1312
1353
/// Used only internally to construct a thread object without spawning.
1313
1354
///
1314
1355
/// # Safety
1315
1356
/// `name` must be valid UTF-8.
1316
1357
pub ( crate ) unsafe fn new ( name : CString ) -> Thread {
1317
- unsafe { Self :: new_inner ( ThreadName :: Other ( name) ) }
1358
+ unsafe { Self :: new_inner ( Some ( name) ) }
1318
1359
}
1319
1360
1320
1361
pub ( crate ) fn new_unnamed ( ) -> Thread {
1321
- unsafe { Self :: new_inner ( ThreadName :: Unnamed ) }
1362
+ unsafe { Self :: new_inner ( None ) }
1322
1363
}
1323
1364
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 )
1327
1376
}
1328
1377
1329
1378
/// # 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 {
1332
1382
// We have to use `unsafe` here to construct the `Parker` in-place,
1333
1383
// which is required for the UNIX implementation.
1334
1384
//
1335
1385
// SAFETY: We pin the Arc immediately after creation, so its address never
1336
1386
// changes.
1337
1387
let inner = unsafe {
1338
- let mut arc = Arc :: < Inner > :: new_uninit ( ) ;
1388
+ let mut arc = Arc :: < OtherInner > :: new_uninit ( ) ;
1339
1389
let ptr = Arc :: get_mut_unchecked ( & mut arc) . as_mut_ptr ( ) ;
1340
1390
addr_of_mut ! ( ( * ptr) . name) . write ( name) ;
1341
1391
addr_of_mut ! ( ( * ptr) . id) . write ( ThreadId :: new ( ) ) ;
1342
1392
Parker :: new_in_place ( addr_of_mut ! ( ( * ptr) . parker) ) ;
1343
1393
Pin :: new_unchecked ( arc. assume_init ( ) )
1344
1394
} ;
1345
1395
1346
- Thread { inner }
1396
+ Self ( Inner :: Other ( inner) )
1347
1397
}
1348
1398
1349
1399
/// Like the public [`park`], but callable on any handle. This is used to
@@ -1352,7 +1402,7 @@ impl Thread {
1352
1402
/// # Safety
1353
1403
/// May only be called from the thread to which this handle belongs.
1354
1404
pub ( crate ) unsafe fn park ( & self ) {
1355
- unsafe { self . inner . as_ref ( ) . parker ( ) . park ( ) }
1405
+ unsafe { self . 0 . parker ( ) . park ( ) }
1356
1406
}
1357
1407
1358
1408
/// Atomically makes the handle's token available if it is not already.
@@ -1388,7 +1438,7 @@ impl Thread {
1388
1438
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1389
1439
#[ inline]
1390
1440
pub fn unpark ( & self ) {
1391
- self . inner . as_ref ( ) . parker ( ) . unpark ( ) ;
1441
+ self . 0 . parker ( ) . unpark ( ) ;
1392
1442
}
1393
1443
1394
1444
/// Gets the thread's unique identifier.
@@ -1408,7 +1458,7 @@ impl Thread {
1408
1458
#[ stable( feature = "thread_id" , since = "1.19.0" ) ]
1409
1459
#[ must_use]
1410
1460
pub fn id ( & self ) -> ThreadId {
1411
- self . inner . id
1461
+ self . 0 . id ( )
1412
1462
}
1413
1463
1414
1464
/// Gets the thread's name.
@@ -1451,15 +1501,7 @@ impl Thread {
1451
1501
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1452
1502
#[ must_use]
1453
1503
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 ( ) ) } )
1463
1505
}
1464
1506
}
1465
1507
0 commit comments