Skip to content

Commit 0d7075e

Browse files
authored
Rollup merge of rust-lang#97524 - ibraheemdev:thread-raw, r=joshtriplett
Add `Thread::{into_raw, from_raw}` Public API: ```rust #![unstable(feature = "thread_raw", issue = "97523")] impl Thread { pub fn into_raw(self) -> *const (); pub unsafe fn from_raw(ptr: *const ()) -> Thread; } ``` ACP: rust-lang/libs-team#200
2 parents 4d7c095 + 01b68b7 commit 0d7075e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

library/std/src/thread/mod.rs

+46
Original file line numberDiff line numberDiff line change
@@ -1503,6 +1503,52 @@ impl Thread {
15031503
self.inner.name.as_str()
15041504
}
15051505

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+
Arc::into_raw(Pin::into_inner(self.inner)) as *const ()
1528+
}
1529+
1530+
/// Constructs a `Thread` from a raw pointer.
1531+
///
1532+
/// The raw pointer must have been previously returned
1533+
/// by a call to [`Thread::into_raw`].
1534+
///
1535+
/// # Safety
1536+
///
1537+
/// This function is unsafe because improper use may lead
1538+
/// to memory unsafety, even if the returned `Thread` is never
1539+
/// accessed.
1540+
///
1541+
/// Creating a `Thread` from a pointer other than one returned
1542+
/// from [`Thread::into_raw`] is **undefined behavior**.
1543+
///
1544+
/// Calling this function twice on the same raw pointer can lead
1545+
/// to a double-free if both `Thread` instances are dropped.
1546+
#[unstable(feature = "thread_raw", issue = "97523")]
1547+
pub unsafe fn from_raw(ptr: *const ()) -> Thread {
1548+
// SAFETY: upheld by caller
1549+
unsafe { Thread { inner: Pin::new_unchecked(Arc::from_raw(ptr as *const Inner)) } }
1550+
}
1551+
15061552
fn cname(&self) -> Option<&CStr> {
15071553
self.inner.name.as_cstr()
15081554
}

0 commit comments

Comments
 (0)