延长线程变量的生命周期 [英] Extend lifetime of a variable for thread
问题描述
我正在从文件中读取字符串,将其按行拆分为向量,然后要对提取的行在单独的线程中进行某些处理.像这样:
I am reading a string from a file, splitting it by lines into a vector and then I want to do something with the extracted lines in separate threads. Like this:
use std::fs::File;
use std::io::prelude::*;
use std::thread;
fn main() {
match File::open("data") {
Ok(mut result) => {
let mut s = String::new();
result.read_to_string(&mut s);
let k : Vec<_> = s.split("\n").collect();
for line in k {
thread::spawn(move || {
println!("nL: {:?}", line);
});
}
}
Err(err) => {
println!("Error {:?}",err);
}
}
}
这当然会引发错误,因为s
将在启动线程之前超出范围:
Of course this throws an error, because s
will go out of scope before the threads are started:
s` does not live long enough
main.rs:9 let k : Vec<_> = s.split("\n").collect();
^
我现在该怎么办?我已经尝试了许多类似Box
或Arc
的方法,但是我无法使其正常工作.我以某种方式需要创建一个s
的副本,该副本也存在于线程中.但是我该怎么做?
What can I do now? I've tried many things like Box
or Arc
, but I couldn't get it working. I somehow need to create a copy of s
which also lives in the threads. But how do I do that?
推荐答案
从根本上讲,问题是line
是s
的借用片段.在这里您实际上无能为力,因为无法保证每个line
都不会超过s
本身.
The problem, fundamentally, is that line
is a borrowed slice into s
. There's really nothing you can do here, since there's no way to guarantee that each line
will not outlive s
itself.
另外,要清楚一点:Rust中绝对没有办法 延长变量的生命周期".根本做不到.
Also, just to be clear: there is absolutely no way in Rust to "extend the lifetime of a variable". It simply cannot be done.
解决此问题的最简单方法是从被借用的line
变为拥有的 .像这样:
The simplest way around this is to go from line
being borrowed to owned. Like so:
use std::thread;
fn main() {
let mut s: String = "One\nTwo\nThree\n".into();
let k : Vec<String> = s.split("\n").map(|s| s.into()).collect();
for line in k {
thread::spawn(move || {
println!("nL: {:?}", line);
});
}
}
.map(|s| s.into())
从&str
转换为String
.由于String
拥有其内容,因此可以安全地将其移动到每个线程的闭包中,并且独立于创建它的线程而存在.
The .map(|s| s.into())
converts from &str
to String
. Since a String
owns its contents, it can be safely moved into each thread's closure, and will live independently of the thread that created it.
注意:您可以使用新的作用域线程API在每晚Rust中执行此操作,但这仍然不稳定.
Note: you could do this in nightly Rust using the new scoped thread API, but that is still unstable.
这篇关于延长线程变量的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!