Mar*_*nko 3 rust async-await rust-tokio reqwest
我正在学习 Rust,特别是并行的多线程和异步请求。
我阅读了文档,但仍然不明白我在哪里犯了错误。我想我知道在哪里,但不知道如何解决它。
主程序.rs
use std::thread;
struct Request {
url: String,
}
impl Request {
fn new(name: &str) -> Request {
Request {
url: name.to_string(),
}
}
async fn call(&self, x: &str) -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::get(x).await;
Ok(())
}
}
#[tokio::main]
async fn main() {
let requests = vec![
Request::new("https://www.google.com/"),
Request::new("https://www.google.com/"),
];
let handles: Vec<_> = requests
.into_iter()
.map(|request| {
thread::spawn(move || async {
request.call(&request.url).await;
})
})
.collect();
for y in handles {
println!("{:?}", y);
}
}
Run Code Online (Sandbox Code Playgroud)
use std::thread;
struct Request {
url: String,
}
impl Request {
fn new(name: &str) -> Request {
Request {
url: name.to_string(),
}
}
async fn call(&self, x: &str) -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::get(x).await;
Ok(())
}
}
#[tokio::main]
async fn main() {
let requests = vec![
Request::new("https://www.google.com/"),
Request::new("https://www.google.com/"),
];
let handles: Vec<_> = requests
.into_iter()
.map(|request| {
thread::spawn(move || async {
request.call(&request.url).await;
})
})
.collect();
for y in handles {
println!("{:?}", y);
}
}
Run Code Online (Sandbox Code Playgroud)
Cargo.toml
[dependencies]
reqwest = "0.10.4"
tokio = { version = "0.2", features = ["full"] }
Run Code Online (Sandbox Code Playgroud)
与闭包一样,async块尽可能弱地捕获其变量。按优先顺序排列:
这是由变量在闭包/异步块中的使用方式决定的。在您的示例中,request仅通过引用使用,因此仅通过引用捕获:
async {
request.call(&request.url).await;
}
Run Code Online (Sandbox Code Playgroud)
但是,您需要将变量的所有权转移到异步块,以便在最终执行 future 时该变量仍然存在。与闭包一样,这是通过move关键字完成的:
thread::spawn(move || async move {
request.call(&request.url).await;
})
Run Code Online (Sandbox Code Playgroud)
也可以看看:
根据您的理解,此时您不太可能想要混合线程和异步。一种本质上是阻塞的,另一种期望代码不阻塞。您应该遵循如何使用 reqwest 执行并行异步 HTTP GET 请求?反而。
也可以看看:
| 归档时间: |
|
| 查看次数: |
1759 次 |
| 最近记录: |