Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use std::thread::Builder instead of std::thread::spawn?

Tags:

rust

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();
like image 835
Angel Angel Avatar asked Apr 18 '16 20:04

Angel Angel


People also ask

What is thread builder?

Interface Thread. Builder. Builder is a preview API of the Java platform. Programs can only use Builder when preview features are enabled.

How many threads can you spawn in Rust?

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.

What is spawned thread?

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.

Can a thread return a value Rust?

A thread can also return a value through its JoinHandle , you can use this to make asynchronous computations (futures might be more appropriate though).


Video Answer


1 Answers

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:

  1. Set a thread name.
  2. Set the stack size.
  3. Handle an error to start the thread.

Use thread::spawn when you don't care about any of those.

like image 145
Shepmaster Avatar answered Nov 09 '22 23:11

Shepmaster