@@ -1503,6 +1503,54 @@ impl Thread {
1503
1503
self . inner . name . as_str ( )
1504
1504
}
1505
1505
1506
+ /// Consumes the `Thread`, returning a raw pointer.
1507
+ ///
1508
+ /// To avoid a memory leak the pointer must be converted
1509
+ /// back into a `Thread` using [`Thread::from_raw`].
1510
+ ///
1511
+ /// # Examples
1512
+ ///
1513
+ /// ```
1514
+ /// #![feature(thread_raw)]
1515
+ ///
1516
+ /// use std::thread::{self, Thread};
1517
+ ///
1518
+ /// let thread = thread::current();
1519
+ /// let id = thread.id();
1520
+ /// let ptr = Thread::into_raw(thread);
1521
+ /// unsafe {
1522
+ /// assert_eq!(Thread::from_raw(ptr).id(), id);
1523
+ /// }
1524
+ /// ```
1525
+ #[ unstable( feature = "thread_raw" , issue = "97523" ) ]
1526
+ pub fn into_raw ( self ) -> * const ( ) {
1527
+ // Safety: We only expose an opaque pointer, which maintains the `Pin` invariant.
1528
+ let inner = unsafe { Pin :: into_inner_unchecked ( self . inner ) } ;
1529
+ Arc :: into_raw ( inner) as * const ( )
1530
+ }
1531
+
1532
+ /// Constructs a `Thread` from a raw pointer.
1533
+ ///
1534
+ /// The raw pointer must have been previously returned
1535
+ /// by a call to [`Thread::into_raw`].
1536
+ ///
1537
+ /// # Safety
1538
+ ///
1539
+ /// This function is unsafe because improper use may lead
1540
+ /// to memory unsafety, even if the returned `Thread` is never
1541
+ /// accessed.
1542
+ ///
1543
+ /// Creating a `Thread` from a pointer other than one returned
1544
+ /// from [`Thread::into_raw`] is **undefined behavior**.
1545
+ ///
1546
+ /// Calling this function twice on the same raw pointer can lead
1547
+ /// to a double-free if both `Thread` instances are dropped.
1548
+ #[ unstable( feature = "thread_raw" , issue = "97523" ) ]
1549
+ pub unsafe fn from_raw ( ptr : * const ( ) ) -> Thread {
1550
+ // Safety: Upheld by caller.
1551
+ unsafe { Thread { inner : Pin :: new_unchecked ( Arc :: from_raw ( ptr as * const Inner ) ) } }
1552
+ }
1553
+
1506
1554
fn cname ( & self ) -> Option < & CStr > {
1507
1555
self . inner . name . as_cstr ( )
1508
1556
}
0 commit comments