如何在不复制的情况下将 str 借给线程?
How can I lend a `str` to a thread without copying?
给定
fn greet(peeps: &str) {
println!("Hello, {}", peeps);
}
我能做到:
fn main() {
let a = "World";
thread::spawn(move || greet(a)).join().unwrap();
}
编译器知道线程的寿命不会超过借用的字符串,但这只是已知 &str
的生命周期为 'static
的特例。当我尝试对函数参数执行相同操作时,它无法编译:
fn indirect(peeps: &str) {
thread::spawn(move || greet(&peeps)).join().unwrap();
// Does not compile, for fear that the thread may outlive peeps
}
然而,对于一个人来说reader,显然线程不能比借用的字符串活得更久。
我找到了两个解决方法:
复制字符串,可以移入线程:
fn indirect(peeps: &str) {
let peeps = peeps.to_string();
thread::spawn(move || greet(&peeps)).join().unwrap();
}
或者,利用著名的弃用 thread::scoped
:
#![feature(scoped)]
fn indirect_scoped(peeps: &str) {
thread::scoped(move || greet(&peeps)).join();
}
我不想为函数参数指定 'static
生命周期,我不希望进行不必要的复制(解决方法 1)并且我不希望使用已弃用的功能(解决方法 2) ).
遇到这种情况我该怎么办?
当您想将借用的数据传递给子线程时,scoped()
的方法是正确的方法。虽然 thread::scoped()
本身由于其不健全而被弃用,但像 crossbeam or scoped_threadpool 这样的替代声音 API 提供了一种在稳定的 Rust 上执行此操作的方法:
extern crate crossbeam;
fn indirect(peeps: &str) {
crossbeam::scope(|scope| {
scope.spawn(|| greet(peeps));
});
}
给定
fn greet(peeps: &str) {
println!("Hello, {}", peeps);
}
我能做到:
fn main() {
let a = "World";
thread::spawn(move || greet(a)).join().unwrap();
}
编译器知道线程的寿命不会超过借用的字符串,但这只是已知 &str
的生命周期为 'static
的特例。当我尝试对函数参数执行相同操作时,它无法编译:
fn indirect(peeps: &str) {
thread::spawn(move || greet(&peeps)).join().unwrap();
// Does not compile, for fear that the thread may outlive peeps
}
然而,对于一个人来说reader,显然线程不能比借用的字符串活得更久。
我找到了两个解决方法:
复制字符串,可以移入线程:
fn indirect(peeps: &str) { let peeps = peeps.to_string(); thread::spawn(move || greet(&peeps)).join().unwrap(); }
或者,利用著名的弃用
thread::scoped
:#![feature(scoped)] fn indirect_scoped(peeps: &str) { thread::scoped(move || greet(&peeps)).join(); }
我不想为函数参数指定 'static
生命周期,我不希望进行不必要的复制(解决方法 1)并且我不希望使用已弃用的功能(解决方法 2) ).
遇到这种情况我该怎么办?
当您想将借用的数据传递给子线程时,scoped()
的方法是正确的方法。虽然 thread::scoped()
本身由于其不健全而被弃用,但像 crossbeam or scoped_threadpool 这样的替代声音 API 提供了一种在稳定的 Rust 上执行此操作的方法:
extern crate crossbeam;
fn indirect(peeps: &str) {
crossbeam::scope(|scope| {
scope.spawn(|| greet(peeps));
});
}