rust - 在作用域线程池中生成线程是否需要额外的时间?

标签 rust

之前我在做一些基于rayon-rs的简单并发 scope功能。我这样做:

rayon::scope::(|s| {
    s.spawn(move |_| {
        // Do something  
    })
})

但是这种方式在s上调用spawn,会花费一些时间来初始化一个新线程。

但是如果我构建一个像这样的线程池:

let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap();

pool.scope(|s| {
    s.spawn(move |_|{
        // Do something
    })
});

以这种方式,在构建线程池后,我在池上调用scope函数,然后在s上调用spawn。我的假设是,通过调用 spawn 函数来初始化新线程不应该花费额外的时间,因为线程已经内置到池中。

我的假设正确吗?如果没有,我可以做什么来实现同样的目标?

感谢您的宝贵时间!

最佳答案

But this way calling spawn on s, some time is spent to initialize a new thread.

rayon::scope(|s| s.spawn(...)) 不会创建新线程;它使用全局线程池。这是documented .

My assumption is, it should not take extra time to initialize a new thread by calling spawn function, because the threads are already built into the pool.

这是正确的,但这同样适用于 rayon::scope(),唯一的区别是它使用 Rayon 内置的全局线程池。

关于rust - 在作用域线程池中生成线程是否需要额外的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69943094/

相关文章:

c - 声明静态变量包含指向另一个静态变量的地址

regex - 无法使用正则表达式 crate : expected (), 中的 `replace_all` 找到的字符串

rust - 在 Rust 中检查两个 HashMap 是否具有相同的键集

rust - 在标称5.1.2中使用位解析器时找不到正确的类型参数

rust - 如何通过将货币转移到另一个帐户而不是使用储备货币来修改昵称托盘(在基板中)以设置昵称?

rust - 错误 : the type of this value must be known in this context

database - rust -我可以使这个dsl​​::find()函数更通用吗?

pointers - 在 Rust 中有效地写入多个字节

rust - 不能将变量借用为可变的,因为在重构解析器时它也被借用为不可变的