I'm trying to request multiple URLs with multiple std::thread
. This is how my code looks so far:
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());
}
}
But I got an error that said:
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 `[closure@src/lib.rs:18:23: 29:10 url:&&str, tx:&std::sync::mpsc::Sender<std::string::String>]`
= note: required by `std::thread::spawn`
When I tried to put the move
in the thread::spawn
:
thread::spawn(move || {
...
I got another error related to lifetime:
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 `[closure@src/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 || {
| ^^^^^^^^^^^^^
So, what is the proper way to send strings from threads through channel here? And how can I solve the lifetime problem in the later error?
Thank you so much!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…