After reading these std::thread::Builder
and std::thread::spawn
I understand their differences (more or less), but is it recommended to use always std::thread::Builder
?.
I do not understand why there are two; can someone explain to me when is best to use one or the other? Perhaps one or the other cannot or should not be used in some cases?
let child: std::thread::JoinHandle<()> = std::thread::spawn(move || {
for a in 0..100{
println!("D");
std::thread::sleep(std::time::Duration::from_millis(50));
}
});
child.join();
let child: Result<std::thread::JoinHandle<()>,_> = std::thread::Builder::new().name("child1".to_string()).spawn(move || {
for a in 0..100{
println!("D");
std::thread::sleep(std::time::Duration::from_millis(50));
}
});
child.unwrap().join();
Interface Thread. Builder. Builder is a preview API of the Java platform. Programs can only use Builder when preview features are enabled.
The threads provided by the Rust standard library are "OS threads", that is, they use the facilities of your operating system. Therefore, a Rust program has no limit imposed by Rust itself, but rather, this limit would result from whatever your OS lets you do.
A "pool" contains a list of available "threads" ready to be used whereas "spawning" refers to actually creating a new thread. The usefulness of "Thread Pooling" lies in "lower time-to-use": creation time overhead is avoided. In terms of "which one is better": it depends.
A thread can also return a value through its JoinHandle , you can use this to make asynchronous computations (futures might be more appropriate though).
The documentation for thread::Builder
answers all of your questions by listing all the functions and types that don't directly correspond to thread::spawn
:
fn name(self, name: String) -> Builder
Names the thread-to-be. Currently the name is used for identification only in panic messages.
fn stack_size(self, size: usize) -> Builder
Sets the size of the stack for the new thread.
fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>> where F: FnOnce() -> T, F: Send + 'static, T: Send + 'static
...
Unlike the spawn free function, this method yields an
io::Result
to capture any failure to create the thread at the OS level.
So a thread::Builder
allows you to:
Use thread::spawn
when you don't care about any of those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With