何时应该使用std :: thread :: Builder而不是std :: thread :: spawn?

6
阅读了这些std::thread::Builderstd::thread::spawn,我大致理解它们的区别,但是否建议总是使用std::thread::Builder呢?
我不明白为什么会有两个;有人能解释一下什么时候最好使用其中一个或另一个吗?也许在某些情况下不能或不应该使用其中一个?
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();
1个回答

7

thread::Builder的文档列出了所有不直接对应于 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.

因此,thread::Builder 允许您:

  1. 设置线程名称。
  2. 设置堆栈大小。
  3. 处理启动线程时的错误。

当您不关心这些问题时,请使用 thread::spawn


谢谢你的回答,出现了一个疑问:在 thread::spawn -> 如果操作系统无法创建线程,则出现紧急情况;使用 Builder::spawn 来从此类错误中恢复。 我不知道这是否会发生,所以想知道是否最好总是使用 Builder。感谢你的时间。 - Angel Angel
1
@AngelAngel 这取决于你打算如何处理失败。如果你有比惊慌更明智的解决方案,那么当然可以使用 Builder - Shepmaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接