@@ -160,18 +160,15 @@ mod tests;
160
160
161
161
use crate :: any:: Any ;
162
162
use crate :: cell:: UnsafeCell ;
163
- use crate :: ffi:: CStr ;
164
163
use crate :: marker:: PhantomData ;
165
164
use crate :: mem:: { self , ManuallyDrop , forget} ;
166
165
use crate :: num:: NonZero ;
167
- use crate :: pin:: Pin ;
168
166
use crate :: sync:: Arc ;
169
167
use crate :: sync:: atomic:: { AtomicUsize , Ordering } ;
170
- use crate :: sys:: sync:: Parker ;
171
168
use crate :: sys:: thread as imp;
172
169
use crate :: sys_common:: { AsInner , IntoInner } ;
173
170
use crate :: time:: { Duration , Instant } ;
174
- use crate :: { env, fmt, io, panic, panicking, str } ;
171
+ use crate :: { env, fmt, io, panic, panicking} ;
175
172
176
173
#[ stable( feature = "scoped_threads" , since = "1.63.0" ) ]
177
174
mod scoped;
@@ -185,6 +182,12 @@ mod current;
185
182
pub use current:: current;
186
183
pub ( crate ) use current:: { current_id, drop_current, set_current, try_current} ;
187
184
185
+ mod thread;
186
+
187
+ #[ stable( feature = "rust1" , since = "1.0.0" ) ]
188
+ pub use thread:: Thread ;
189
+ pub ( crate ) use thread:: { is_main, set_main_thread} ;
190
+
188
191
////////////////////////////////////////////////////////////////////////////////
189
192
// Thread-local storage
190
193
////////////////////////////////////////////////////////////////////////////////
@@ -477,11 +480,7 @@ impl Builder {
477
480
amt
478
481
} ) ;
479
482
480
- let id = ThreadId :: new ( ) ;
481
- let my_thread = match name {
482
- Some ( name) => Thread :: new ( id, name. into ( ) ) ,
483
- None => Thread :: new_unnamed ( id) ,
484
- } ;
483
+ let my_thread = Thread :: new ( ThreadId :: new ( ) , name) ;
485
484
let their_thread = my_thread. clone ( ) ;
486
485
487
486
let my_packet: Arc < Packet < ' scope , T > > = Arc :: new ( Packet {
@@ -1125,7 +1124,7 @@ pub fn park_timeout(dur: Duration) {
1125
1124
let guard = PanicGuard ;
1126
1125
// SAFETY: park_timeout is called on the parker owned by this thread.
1127
1126
unsafe {
1128
- current ( ) . inner . as_ref ( ) . parker ( ) . park_timeout ( dur) ;
1127
+ current ( ) . park_timeout ( dur) ;
1129
1128
}
1130
1129
// No panic occurred, do not abort.
1131
1130
forget ( guard) ;
@@ -1208,7 +1207,7 @@ impl ThreadId {
1208
1207
}
1209
1208
}
1210
1209
1211
- #[ cfg ( not ( target_thread_local ) ) ]
1210
+ #[ allow ( unused ) ]
1212
1211
fn from_u64 ( v : u64 ) -> Option < ThreadId > {
1213
1212
NonZero :: new ( v) . map ( ThreadId )
1214
1213
}
@@ -1228,300 +1227,6 @@ impl ThreadId {
1228
1227
}
1229
1228
}
1230
1229
1231
- ////////////////////////////////////////////////////////////////////////////////
1232
- // Thread
1233
- ////////////////////////////////////////////////////////////////////////////////
1234
-
1235
- /// The internal representation of a `Thread`'s name.
1236
- enum ThreadName {
1237
- Main ,
1238
- Other ( ThreadNameString ) ,
1239
- Unnamed ,
1240
- }
1241
-
1242
- // This module ensures private fields are kept private, which is necessary to enforce the safety requirements.
1243
- mod thread_name_string {
1244
- use core:: str;
1245
-
1246
- use super :: ThreadName ;
1247
- use crate :: ffi:: { CStr , CString } ;
1248
-
1249
- /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated.
1250
- pub ( crate ) struct ThreadNameString {
1251
- inner : CString ,
1252
- }
1253
- impl core:: ops:: Deref for ThreadNameString {
1254
- type Target = CStr ;
1255
- fn deref ( & self ) -> & CStr {
1256
- & self . inner
1257
- }
1258
- }
1259
- impl From < String > for ThreadNameString {
1260
- fn from ( s : String ) -> Self {
1261
- Self {
1262
- inner : CString :: new ( s) . expect ( "thread name may not contain interior null bytes" ) ,
1263
- }
1264
- }
1265
- }
1266
- impl ThreadName {
1267
- pub fn as_cstr ( & self ) -> Option < & CStr > {
1268
- match self {
1269
- ThreadName :: Main => Some ( c"main" ) ,
1270
- ThreadName :: Other ( other) => Some ( other) ,
1271
- ThreadName :: Unnamed => None ,
1272
- }
1273
- }
1274
-
1275
- pub fn as_str ( & self ) -> Option < & str > {
1276
- // SAFETY: `as_cstr` can only return `Some` for a fixed CStr or a `ThreadNameString`,
1277
- // which is guaranteed to be UTF-8.
1278
- self . as_cstr ( ) . map ( |s| unsafe { str:: from_utf8_unchecked ( s. to_bytes ( ) ) } )
1279
- }
1280
- }
1281
- }
1282
- pub ( crate ) use thread_name_string:: ThreadNameString ;
1283
-
1284
- /// The internal representation of a `Thread` handle
1285
- struct Inner {
1286
- name : ThreadName , // Guaranteed to be UTF-8
1287
- id : ThreadId ,
1288
- parker : Parker ,
1289
- }
1290
-
1291
- impl Inner {
1292
- fn parker ( self : Pin < & Self > ) -> Pin < & Parker > {
1293
- unsafe { Pin :: map_unchecked ( self , |inner| & inner. parker ) }
1294
- }
1295
- }
1296
-
1297
- #[ derive( Clone ) ]
1298
- #[ stable( feature = "rust1" , since = "1.0.0" ) ]
1299
- /// A handle to a thread.
1300
- ///
1301
- /// Threads are represented via the `Thread` type, which you can get in one of
1302
- /// two ways:
1303
- ///
1304
- /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`]
1305
- /// function, and calling [`thread`][`JoinHandle::thread`] on the
1306
- /// [`JoinHandle`].
1307
- /// * By requesting the current thread, using the [`thread::current`] function.
1308
- ///
1309
- /// The [`thread::current`] function is available even for threads not spawned
1310
- /// by the APIs of this module.
1311
- ///
1312
- /// There is usually no need to create a `Thread` struct yourself, one
1313
- /// should instead use a function like `spawn` to create new threads, see the
1314
- /// docs of [`Builder`] and [`spawn`] for more details.
1315
- ///
1316
- /// [`thread::current`]: current::current
1317
- pub struct Thread {
1318
- inner : Pin < Arc < Inner > > ,
1319
- }
1320
-
1321
- impl Thread {
1322
- /// Used only internally to construct a thread object without spawning.
1323
- pub ( crate ) fn new ( id : ThreadId , name : String ) -> Thread {
1324
- Self :: new_inner ( id, ThreadName :: Other ( name. into ( ) ) )
1325
- }
1326
-
1327
- pub ( crate ) fn new_unnamed ( id : ThreadId ) -> Thread {
1328
- Self :: new_inner ( id, ThreadName :: Unnamed )
1329
- }
1330
-
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 )
1334
- }
1335
-
1336
- fn new_inner ( id : ThreadId , name : ThreadName ) -> Thread {
1337
- // We have to use `unsafe` here to construct the `Parker` in-place,
1338
- // which is required for the UNIX implementation.
1339
- //
1340
- // SAFETY: We pin the Arc immediately after creation, so its address never
1341
- // changes.
1342
- let inner = unsafe {
1343
- let mut arc = Arc :: < Inner > :: new_uninit ( ) ;
1344
- let ptr = Arc :: get_mut_unchecked ( & mut arc) . as_mut_ptr ( ) ;
1345
- ( & raw mut ( * ptr) . name ) . write ( name) ;
1346
- ( & raw mut ( * ptr) . id ) . write ( id) ;
1347
- Parker :: new_in_place ( & raw mut ( * ptr) . parker ) ;
1348
- Pin :: new_unchecked ( arc. assume_init ( ) )
1349
- } ;
1350
-
1351
- Thread { inner }
1352
- }
1353
-
1354
- /// Like the public [`park`], but callable on any handle. This is used to
1355
- /// allow parking in TLS destructors.
1356
- ///
1357
- /// # Safety
1358
- /// May only be called from the thread to which this handle belongs.
1359
- pub ( crate ) unsafe fn park ( & self ) {
1360
- unsafe { self . inner . as_ref ( ) . parker ( ) . park ( ) }
1361
- }
1362
-
1363
- /// Atomically makes the handle's token available if it is not already.
1364
- ///
1365
- /// Every thread is equipped with some basic low-level blocking support, via
1366
- /// the [`park`][park] function and the `unpark()` method. These can be
1367
- /// used as a more CPU-efficient implementation of a spinlock.
1368
- ///
1369
- /// See the [park documentation][park] for more details.
1370
- ///
1371
- /// # Examples
1372
- ///
1373
- /// ```
1374
- /// use std::thread;
1375
- /// use std::time::Duration;
1376
- ///
1377
- /// let parked_thread = thread::Builder::new()
1378
- /// .spawn(|| {
1379
- /// println!("Parking thread");
1380
- /// thread::park();
1381
- /// println!("Thread unparked");
1382
- /// })
1383
- /// .unwrap();
1384
- ///
1385
- /// // Let some time pass for the thread to be spawned.
1386
- /// thread::sleep(Duration::from_millis(10));
1387
- ///
1388
- /// println!("Unpark the thread");
1389
- /// parked_thread.thread().unpark();
1390
- ///
1391
- /// parked_thread.join().unwrap();
1392
- /// ```
1393
- #[ stable( feature = "rust1" , since = "1.0.0" ) ]
1394
- #[ inline]
1395
- pub fn unpark ( & self ) {
1396
- self . inner . as_ref ( ) . parker ( ) . unpark ( ) ;
1397
- }
1398
-
1399
- /// Gets the thread's unique identifier.
1400
- ///
1401
- /// # Examples
1402
- ///
1403
- /// ```
1404
- /// use std::thread;
1405
- ///
1406
- /// let other_thread = thread::spawn(|| {
1407
- /// thread::current().id()
1408
- /// });
1409
- ///
1410
- /// let other_thread_id = other_thread.join().unwrap();
1411
- /// assert!(thread::current().id() != other_thread_id);
1412
- /// ```
1413
- #[ stable( feature = "thread_id" , since = "1.19.0" ) ]
1414
- #[ must_use]
1415
- pub fn id ( & self ) -> ThreadId {
1416
- self . inner . id
1417
- }
1418
-
1419
- /// Gets the thread's name.
1420
- ///
1421
- /// For more information about named threads, see
1422
- /// [this module-level documentation][naming-threads].
1423
- ///
1424
- /// # Examples
1425
- ///
1426
- /// Threads by default have no name specified:
1427
- ///
1428
- /// ```
1429
- /// use std::thread;
1430
- ///
1431
- /// let builder = thread::Builder::new();
1432
- ///
1433
- /// let handler = builder.spawn(|| {
1434
- /// assert!(thread::current().name().is_none());
1435
- /// }).unwrap();
1436
- ///
1437
- /// handler.join().unwrap();
1438
- /// ```
1439
- ///
1440
- /// Thread with a specified name:
1441
- ///
1442
- /// ```
1443
- /// use std::thread;
1444
- ///
1445
- /// let builder = thread::Builder::new()
1446
- /// .name("foo".into());
1447
- ///
1448
- /// let handler = builder.spawn(|| {
1449
- /// assert_eq!(thread::current().name(), Some("foo"))
1450
- /// }).unwrap();
1451
- ///
1452
- /// handler.join().unwrap();
1453
- /// ```
1454
- ///
1455
- /// [naming-threads]: ./index.html#naming-threads
1456
- #[ stable( feature = "rust1" , since = "1.0.0" ) ]
1457
- #[ must_use]
1458
- pub fn name ( & self ) -> Option < & str > {
1459
- self . inner . name . as_str ( )
1460
- }
1461
-
1462
- /// Consumes the `Thread`, returning a raw pointer.
1463
- ///
1464
- /// To avoid a memory leak the pointer must be converted
1465
- /// back into a `Thread` using [`Thread::from_raw`].
1466
- ///
1467
- /// # Examples
1468
- ///
1469
- /// ```
1470
- /// #![feature(thread_raw)]
1471
- ///
1472
- /// use std::thread::{self, Thread};
1473
- ///
1474
- /// let thread = thread::current();
1475
- /// let id = thread.id();
1476
- /// let ptr = Thread::into_raw(thread);
1477
- /// unsafe {
1478
- /// assert_eq!(Thread::from_raw(ptr).id(), id);
1479
- /// }
1480
- /// ```
1481
- #[ unstable( feature = "thread_raw" , issue = "97523" ) ]
1482
- pub fn into_raw ( self ) -> * const ( ) {
1483
- // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant.
1484
- let inner = unsafe { Pin :: into_inner_unchecked ( self . inner ) } ;
1485
- Arc :: into_raw ( inner) as * const ( )
1486
- }
1487
-
1488
- /// Constructs a `Thread` from a raw pointer.
1489
- ///
1490
- /// The raw pointer must have been previously returned
1491
- /// by a call to [`Thread::into_raw`].
1492
- ///
1493
- /// # Safety
1494
- ///
1495
- /// This function is unsafe because improper use may lead
1496
- /// to memory unsafety, even if the returned `Thread` is never
1497
- /// accessed.
1498
- ///
1499
- /// Creating a `Thread` from a pointer other than one returned
1500
- /// from [`Thread::into_raw`] is **undefined behavior**.
1501
- ///
1502
- /// Calling this function twice on the same raw pointer can lead
1503
- /// to a double-free if both `Thread` instances are dropped.
1504
- #[ unstable( feature = "thread_raw" , issue = "97523" ) ]
1505
- pub unsafe fn from_raw ( ptr : * const ( ) ) -> Thread {
1506
- // Safety: Upheld by caller.
1507
- unsafe { Thread { inner : Pin :: new_unchecked ( Arc :: from_raw ( ptr as * const Inner ) ) } }
1508
- }
1509
-
1510
- fn cname ( & self ) -> Option < & CStr > {
1511
- self . inner . name . as_cstr ( )
1512
- }
1513
- }
1514
-
1515
- #[ stable( feature = "rust1" , since = "1.0.0" ) ]
1516
- impl fmt:: Debug for Thread {
1517
- fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
1518
- f. debug_struct ( "Thread" )
1519
- . field ( "id" , & self . id ( ) )
1520
- . field ( "name" , & self . name ( ) )
1521
- . finish_non_exhaustive ( )
1522
- }
1523
- }
1524
-
1525
1230
////////////////////////////////////////////////////////////////////////////////
1526
1231
// JoinHandle
1527
1232
////////////////////////////////////////////////////////////////////////////////
0 commit comments