@@ -1230,6 +1230,52 @@ impl Thread {
1230
1230
self . cname ( ) . map ( |s| unsafe { str:: from_utf8_unchecked ( s. to_bytes ( ) ) } )
1231
1231
}
1232
1232
1233
+ /// Consumes the `Thread`, returning a raw pointer.
1234
+ ///
1235
+ /// To avoid a memory leak the pointer must be converted
1236
+ /// back into a `Thread` using [`Thread::from_raw`].
1237
+ ///
1238
+ /// # Examples
1239
+ ///
1240
+ /// ```
1241
+ /// #![feature(thread_raw)]
1242
+ ///
1243
+ /// use std::thread::{self, Thread};
1244
+ ///
1245
+ /// let thread = thread::current();
1246
+ /// let id = thread.id();
1247
+ /// let ptr = Thread::into_raw(thread);
1248
+ /// unsafe {
1249
+ /// assert_eq!(Thread::from_raw(ptr).id(), id);
1250
+ /// }
1251
+ /// ```
1252
+ #[ unstable( feature = "thread_raw" , issue = "97523" ) ]
1253
+ pub fn into_raw ( self ) -> * const ( ) {
1254
+ Arc :: into_raw ( Pin :: into_inner ( self . inner ) ) as * const ( )
1255
+ }
1256
+
1257
+ /// Constructs a `Thread` from a raw pointer.
1258
+ ///
1259
+ /// The raw pointer must have been previously returned
1260
+ /// by a call to [`Thread::into_raw`].
1261
+ ///
1262
+ /// # Safety
1263
+ ///
1264
+ /// This function is unsafe because improper use may lead
1265
+ /// to memory unsafety, even if the returned `Thread` is never
1266
+ /// accessed.
1267
+ ///
1268
+ /// Creating a `Thread` from a pointer other than one returned
1269
+ /// from [`Thread::into_raw`] is **undefined behavior**.
1270
+ ///
1271
+ /// Calling this function twice on the same raw pointer can lead
1272
+ /// to a double-free if both `Thread` instances are dropped.
1273
+ #[ unstable( feature = "thread_raw" , issue = "97523" ) ]
1274
+ pub unsafe fn from_raw ( ptr : * const ( ) ) -> Thread {
1275
+ // SAFETY: upheld by caller
1276
+ unsafe { Thread { inner : Pin :: new_unchecked ( Arc :: from_raw ( ptr as * const Inner ) ) } }
1277
+ }
1278
+
1233
1279
fn cname ( & self ) -> Option < & CStr > {
1234
1280
self . inner . name . as_deref ( )
1235
1281
}
0 commit comments