我试图请求多个网址与多个std::thread
。这是我的代码看起来是迄今:Rust中的线程之间共享字符串
fn fetch(urls: Vec<&str>) {
let (tx, rx) = mpsc::channel();
for url in urls {
let tx = tx.clone();
thread::spawn(|| {
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
let client = Client::with_connector(connector);
let mut res = client.get(url).send().unwrap();
let mut result = String::new();
res.read_to_string(&mut result);
tx.send(result).unwrap();
});
}
//let mut result: Vec<String> = vec![];
for _ in urls {
println!("{}", rx.recv().unwrap());
}
}
但我得到一个错误,说:
error[E0277]: the trait bound `std::sync::mpsc::Sender<std::string::String>: std::marker::Sync` is not satisfied
--> src/lib.rs:18:9
|
18 | thread::spawn(|| {
| ^^^^^^^^^^^^^ the trait `std::marker::Sync` is not implemented for `std::sync::mpsc::Sender<std::string::String>`
|
= note: `std::sync::mpsc::Sender<std::string::String>` cannot be shared between threads safely
= note: required because of the requirements on the impl of `std::marker::Send` for `&std::sync::mpsc::Sender<std::string::String>`
= note: required because it appears within the type `[[email protected]/lib.rs:18:23: 29:10 url:&&str, tx:&std::sync::mpsc::Sender<std::string::String>]`
= note: required by `std::thread::spawn`
当我试图把move
在thread::spawn
:
thread::spawn(move || {
...
我得到另一个与生命有关的错误:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:15:16
|
15 | for url in urls {
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 12:26...
--> src/lib.rs:12:27
|
12 | fn fetch(urls: Vec<&str>) {
| ^
note: ...so that expression is assignable (expected std::vec::Vec<&str>, found std::vec::Vec<&str>)
--> src/lib.rs:15:16
|
15 | for url in urls {
| ^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[[email protected]/lib.rs:18:23: 27:10 url:&str, tx:std::sync::mpsc::Sender<std::string::String>]` will meet its required lifetime bounds
--> src/lib.rs:18:9
|
18 | thread::spawn(move || {
| ^^^^^^^^^^^^^
那么,在这里通过通道从线程发送字符串的正确方法是什么?我怎样才能解决后来的错误生活中的问题?
非常感谢!
非常感谢您提供非常详细的答案!第二个解决方案'&'static str'真的对我有用! –