pub struct Builder { /* private fields */ }
Expand description
Thread factory, which can be used in order to configure the properties of a new thread.
Methods can be chained on it in order to configure it.
The two configurations available are:
name
: specifies an associated name for the threadstack_size
: specifies the desired stack size for the thread
The spawn
method will take ownership of the builder and create an
io::Result
to the thread handle with the given configuration.
The thread::spawn
free function uses a Builder
with default
configuration and unwrap
s its return value.
You may want to use spawn
instead of thread::spawn
, when you want
to recover from a failure to launch a thread, indeed the free function will
panic where the Builder
method will return a io::Result
.
§Examples
use std::thread;
let builder = thread::Builder::new();
let handler = builder.spawn(|| {
// thread code
}).unwrap();
handler.join().unwrap();
Implementations§
source§impl Builder
impl Builder
1.63.0 · sourcepub fn spawn_scoped<'scope, 'env, F, T>(
self,
scope: &'scope Scope<'scope, 'env>,
f: F,
) -> Result<ScopedJoinHandle<'scope, T>, Error>
Available on crate feature std
only.
pub fn spawn_scoped<'scope, 'env, F, T>( self, scope: &'scope Scope<'scope, 'env>, f: F, ) -> Result<ScopedJoinHandle<'scope, T>, Error>
std
only.Spawns a new scoped thread using the settings set through this Builder
.
Unlike Scope::spawn
, this method yields an io::Result
to
capture any failure to create the thread at the OS level.
§Panics
Panics if a thread name was set and it contained null bytes.
§Example
use std::thread;
let mut a = vec![1, 2, 3];
let mut x = 0;
thread::scope(|s| {
thread::Builder::new()
.name("first".to_string())
.spawn_scoped(s, ||
{
println!("hello from the {:?} scoped thread", thread::current().name());
// We can borrow `a` here.
dbg!(&a);
})
.unwrap();
thread::Builder::new()
.name("second".to_string())
.spawn_scoped(s, ||
{
println!("hello from the {:?} scoped thread", thread::current().name());
// We can even mutably borrow `x` here,
// because no other threads are using it.
x += a[0] + a[2];
})
.unwrap();
println!("hello from the main thread");
});
// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());
source§impl Builder
impl Builder
1.0.0 · sourcepub fn new() -> Builder
Available on crate feature std
only.
pub fn new() -> Builder
std
only.Generates the base configuration for spawning a thread, from which configuration methods can be chained.
§Examples
use std::thread;
let builder = thread::Builder::new()
.name("foo".into())
.stack_size(32 * 1024);
let handler = builder.spawn(|| {
// thread code
}).unwrap();
handler.join().unwrap();
1.0.0 · sourcepub fn name(self, name: String) -> Builder
Available on crate feature std
only.
pub fn name(self, name: String) -> Builder
std
only.Names the thread-to-be. Currently the name is used for identification only in panic messages.
The name must not contain null bytes (\0
).
For more information about named threads, see this module-level documentation.
§Examples
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();
1.0.0 · sourcepub fn stack_size(self, size: usize) -> Builder
Available on crate feature std
only.
pub fn stack_size(self, size: usize) -> Builder
std
only.Sets the size of the stack (in bytes) for the new thread.
The actual stack size may be greater than this value if the platform specifies a minimal stack size.
For more information about the stack size for threads, see this module-level documentation.
§Examples
use std::thread;
let builder = thread::Builder::new().stack_size(32 * 1024);
1.0.0 · sourcepub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>, Error>
Available on crate feature std
only.
pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>, Error>
std
only.Spawns a new thread by taking ownership of the Builder
, and returns an
io::Result
to its JoinHandle
.
The spawned thread may outlive the caller (unless the caller thread is the main thread; the whole process is terminated when the main thread finishes). The join handle can be used to block on termination of the spawned thread, including recovering its panics.
For a more complete documentation see thread::spawn
.
§Errors
Unlike the spawn
free function, this method yields an
io::Result
to capture any failure to create the thread at
the OS level.
§Panics
Panics if a thread name was set and it contained null bytes.
§Examples
use std::thread;
let builder = thread::Builder::new();
let handler = builder.spawn(|| {
// thread code
}).unwrap();
handler.join().unwrap();
sourcepub unsafe fn spawn_unchecked<'a, F, T>(
self,
f: F,
) -> Result<JoinHandle<T>, Error>
🔬This is a nightly-only experimental API. (thread_spawn_unchecked
)Available on crate feature std
only.
pub unsafe fn spawn_unchecked<'a, F, T>( self, f: F, ) -> Result<JoinHandle<T>, Error>
thread_spawn_unchecked
)std
only.Spawns a new thread without any lifetime restrictions by taking ownership
of the Builder
, and returns an io::Result
to its JoinHandle
.
The spawned thread may outlive the caller (unless the caller thread is the main thread; the whole process is terminated when the main thread finishes). The join handle can be used to block on termination of the spawned thread, including recovering its panics.
This method is identical to thread::Builder::spawn
,
except for the relaxed lifetime bounds, which render it unsafe.
For a more complete documentation see thread::spawn
.
§Errors
Unlike the spawn
free function, this method yields an
io::Result
to capture any failure to create the thread at
the OS level.
§Panics
Panics if a thread name was set and it contained null bytes.
§Safety
The caller has to ensure that the spawned thread does not outlive any references in the supplied thread closure and its return type. This can be guaranteed in two ways:
- ensure that
join
is called before any referenced data is dropped - use only types with
'static
lifetime bounds, i.e., those with no or only'static
references (boththread::Builder::spawn
andthread::spawn
enforce this property statically)
§Examples
#![feature(thread_spawn_unchecked)]
use std::thread;
let builder = thread::Builder::new();
let x = 1;
let thread_x = &x;
let handler = unsafe {
builder.spawn_unchecked(move || {
println!("x = {}", *thread_x);
}).unwrap()
};
// caller has to ensure `join()` is called, otherwise
// it is possible to access freed memory if `x` gets
// dropped before the thread closure is executed!
handler.join().unwrap();
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Builder
impl RefUnwindSafe for Builder
impl Send for Builder
impl Sync for Builder
impl Unpin for Builder
impl UnwindSafe for Builder
Blanket Implementations§
source§impl<T> Also for T
impl<T> Also for T
source§impl<T, Res> Apply<Res> for Twhere
T: ?Sized,
impl<T, Res> Apply<Res> for Twhere
T: ?Sized,
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§const LITTLE_ENDIAN: bool = true
const LITTLE_ENDIAN: bool = true
source§const BIG_ENDIAN: bool = false
const BIG_ENDIAN: bool = false
source§fn byte_align(&self) -> usize ⓘ
fn byte_align(&self) -> usize ⓘ
source§impl<T> ExtAny for T
impl<T> ExtAny for T
source§fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
source§impl<T> ExtMem for Twhere
T: ?Sized,
impl<T> ExtMem for Twhere
T: ?Sized,
source§const NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
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§fn mem_as_bytes(&self) -> &[u8] ⓘ
fn mem_as_bytes(&self) -> &[u8] ⓘ
unsafe_slice
only.