pub struct Thread { /* private fields */ }std only.Expand description
🧵
std
A handle to a thread.
📍work/thread re-exported from std::thread
See also the ThreadExt trait.
📜
A handle to a thread.
Threads are represented via the Thread type, which you can get in one of
two ways:
- By spawning a new thread, e.g., using the
thread::spawnfunction, and callingthreadon theJoinHandle. - By requesting the current thread, using the
thread::currentfunction.
The thread::current function is available even for threads not spawned
by the APIs of this module.
There is usually no need to create a Thread struct yourself, one
should instead use a function like spawn to create new threads, see the
docs of Builder and spawn for more details.
Implementations§
Source§impl Thread
impl Thread
1.0.0 · Sourcepub fn unpark(&self)
pub fn unpark(&self)
Atomically makes the handle’s token available if it is not already.
Every thread is equipped with some basic low-level blocking support, via
the park function and the unpark() method. These can be used as a
more CPU-efficient implementation of a spinlock.
See the park documentation for more details.
§Examples
use std::thread;
use std::time::Duration;
use std::sync::atomic::{AtomicBool, Ordering};
static QUEUED: AtomicBool = AtomicBool::new(false);
let parked_thread = thread::Builder::new()
.spawn(|| {
println!("Parking thread");
QUEUED.store(true, Ordering::Release);
thread::park();
println!("Thread unparked");
})
.unwrap();
// Let some time pass for the thread to be spawned.
thread::sleep(Duration::from_millis(10));
// Wait until the other thread is queued.
// This is crucial! It guarantees that the `unpark` below is not consumed
// by some other code in the parked thread (e.g. inside `println!`).
while !QUEUED.load(Ordering::Acquire) {
// Spinning is of course inefficient; in practice, this would more likely be
// a dequeue where we have no work to do if there's nobody queued.
std::hint::spin_loop();
}
println!("Unpark the thread");
parked_thread.thread().unpark();
parked_thread.join().unwrap();1.19.0 · Sourcepub fn id(&self) -> ThreadId
pub fn id(&self) -> ThreadId
Gets the thread’s unique identifier.
§Examples
use std::thread;
let other_thread = thread::spawn(|| {
thread::current().id()
});
let other_thread_id = other_thread.join().unwrap();
assert!(thread::current().id() != other_thread_id);1.0.0 · Sourcepub fn name(&self) -> Option<&str> ⓘ
pub fn name(&self) -> Option<&str> ⓘ
Gets the thread’s name.
For more information about named threads, see this module-level documentation.
§Examples
Threads by default have no name specified:
use std::thread;
let builder = thread::Builder::new();
let handler = builder.spawn(|| {
assert!(thread::current().name().is_none());
}).unwrap();
handler.join().unwrap();Thread with a specified name:
use std::thread;
let builder = thread::Builder::new()
.name("foo".into());
let handler = builder.spawn(|| {
assert_eq!(thread::current().name(), Some("foo"))
}).unwrap();
handler.join().unwrap();Sourcepub fn into_raw(self) -> *const ()
🔬This is a nightly-only experimental API. (thread_raw)
pub fn into_raw(self) -> *const ()
thread_raw)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. The pointer is
guaranteed to be aligned to at least 8 bytes.
§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);
}Sourcepub unsafe fn from_raw(ptr: *const ()) -> Thread ⓘ
🔬This is a nightly-only experimental API. (thread_raw)
pub unsafe fn from_raw(ptr: *const ()) -> Thread ⓘ
thread_raw)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.
Trait Implementations§
Source§impl ThreadExt for Thread
impl ThreadExt for Thread
Source§fn panicking() -> bool
fn panicking() -> bool
Source§fn available_parallelism() -> Result<usize, IoError> ⓘ
fn available_parallelism() -> Result<usize, IoError> ⓘ
Source§fn park_timeout(duration: Duration)
fn park_timeout(duration: Duration)
Source§fn scope<'env, F, T>(f: F) -> Twhere
F: for<'scope> FnOnce(&'scope ThreadScope<'scope, 'env>) -> T,
fn scope<'env, F, T>(f: F) -> Twhere
F: for<'scope> FnOnce(&'scope ThreadScope<'scope, 'env>) -> T,
Source§fn sleep(duration: Duration)
fn sleep(duration: Duration)
Source§fn sleep_ms(milliseconds: u64)
fn sleep_ms(milliseconds: u64)
milliseconds.Source§fn sleep_us(microseconds: u64)
fn sleep_us(microseconds: u64)
nanoseconds.Source§fn sleep_ns(nanoseconds: u64)
fn sleep_ns(nanoseconds: u64)
nanoseconds.Source§fn spawn<F, T>(f: F) -> ThreadJoinHandle<T>
fn spawn<F, T>(f: F) -> ThreadJoinHandle<T>
ThreadJoinHandle for it. Read moreAuto Trait Implementations§
impl Freeze for Thread
impl RefUnwindSafe for Thread
impl Send for Thread
impl Sync for Thread
impl Unpin for Thread
impl UnsafeUnpin for Thread
impl UnwindSafe for Thread
Blanket Implementations§
Source§impl<T> AnyExt for T
impl<T> AnyExt for T
Source§fn type_hash_with<H: Hasher>(&self, hasher: H) -> u64
fn type_hash_with<H: Hasher>(&self, hasher: H) -> u64
TypeId of Self using a custom hasher.Source§fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
Source§fn as_any_box(self: Box<Self>) -> Box<dyn Any>where
Self: Sized,
fn as_any_box(self: Box<Self>) -> Box<dyn Any>where
Self: Sized,
alloc only.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> ByteSized for T
impl<T> ByteSized for T
Source§const BYTE_ALIGN: usize = _
const BYTE_ALIGN: usize = _
Source§fn byte_align(&self) -> usize
fn byte_align(&self) -> usize
Source§fn ptr_size_ratio(&self) -> [usize; 2]
fn ptr_size_ratio(&self) -> [usize; 2]
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> MemExt for Twhere
T: ?Sized,
impl<T> MemExt for Twhere
T: ?Sized,
Source§const NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
Source§fn mem_align_of<T>() -> usize
fn mem_align_of<T>() -> usize
Source§fn mem_align_of_val(&self) -> usize
fn mem_align_of_val(&self) -> usize
Source§fn mem_size_of<T>() -> usize
fn mem_size_of<T>() -> usize
Source§fn mem_size_of_val(&self) -> usize
fn mem_size_of_val(&self) -> usize
Source§fn mem_needs_drop(&self) -> bool
fn mem_needs_drop(&self) -> bool
true if dropping values of this type matters. Read moreSource§fn mem_forget(self)where
Self: Sized,
fn mem_forget(self)where
Self: Sized,
self without running its destructor. Read moreSource§fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
Source§unsafe fn mem_zeroed<T>() -> T
unsafe fn mem_zeroed<T>() -> T
unsafe_layout only.T represented by the all-zero byte-pattern. Read moreSource§unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe_layout only.T represented by the all-zero byte-pattern. Read moreSource§fn mem_as_bytes(&self) -> &[u8] ⓘ
fn mem_as_bytes(&self) -> &[u8] ⓘ
unsafe_slice only.