Skip to content

Commit

Permalink
Rollup merge of rust-lang#97524 - ibraheemdev:thread-raw, r=joshtriplett
Browse files Browse the repository at this point in the history
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
  • Loading branch information
tgross35 authored Aug 21, 2024
2 parents 4d7c095 + 01b68b7 commit 0d7075e
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions library/std/src/thread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1503,6 +1503,52 @@ impl Thread {
self.inner.name.as_str()
}

/// Consumes the `Thread`, returning a raw pointer.
///
/// To avoid a memory leak the pointer must be converted
/// back into a `Thread` using [`Thread::from_raw`].
///
/// # Examples
///
/// ```
/// #![feature(thread_raw)]
///
/// use std::thread::{self, Thread};
///
/// let thread = thread::current();
/// let id = thread.id();
/// let ptr = Thread::into_raw(thread);
/// unsafe {
/// assert_eq!(Thread::from_raw(ptr).id(), id);
/// }
/// ```
#[unstable(feature = "thread_raw", issue = "97523")]
pub fn into_raw(self) -> *const () {
Arc::into_raw(Pin::into_inner(self.inner)) as *const ()
}

/// Constructs a `Thread` from a raw pointer.
///
/// The raw pointer must have been previously returned
/// by a call to [`Thread::into_raw`].
///
/// # Safety
///
/// This function is unsafe because improper use may lead
/// to memory unsafety, even if the returned `Thread` is never
/// accessed.
///
/// Creating a `Thread` from a pointer other than one returned
/// from [`Thread::into_raw`] is **undefined behavior**.
///
/// Calling this function twice on the same raw pointer can lead
/// to a double-free if both `Thread` instances are dropped.
#[unstable(feature = "thread_raw", issue = "97523")]
pub unsafe fn from_raw(ptr: *const ()) -> Thread {
// SAFETY: upheld by caller
unsafe { Thread { inner: Pin::new_unchecked(Arc::from_raw(ptr as *const Inner)) } }
}

fn cname(&self) -> Option<&CStr> {
self.inner.name.as_cstr()
}
Expand Down

0 comments on commit 0d7075e

Please sign in to comment.