gpt4 book ai didi

multithreading - 我如何装箱 Arc 和 Mutexed 变量?

转载 作者:行者123 更新时间:2023-11-29 08:35:12 26 4
gpt4 key购买 nike

以下代码在闭包中获取一些变量并返回包含该数据的结构。

即使我装箱结构并克隆变量,我也无法返回包含该数据的结构;他们不可能脱离这个范围。我考虑过使用回调闭包,但我真的不想那样做。有没有办法在没有回调的情况下将它们取出来?

pub fn get(addr: &str) -> std::io::Result<Box<Response>> {
use std::sync::{Arc, Mutex};
let mut crl = curl::easy::Easy::new();
crl.url(format!("{}{}", API_ADDR, addr).as_str()).unwrap();

// extract headers
let headers: Vec<String> = Vec::with_capacity(10);
let headers = Arc::new(Mutex::new(headers));
{
let headers = headers.clone();
crl.header_function(move |h| {
let mut headers = headers.lock().unwrap();
(*headers).push(String::from_utf8_lossy(h).into_owned());
true
})
.unwrap();
}

// extract body
let body = Arc::new(Mutex::new(String::with_capacity(1024)));
{
let body = body.clone();
crl.write_function(move |b| {
let mut body = body.lock().unwrap();
body.push_str(std::str::from_utf8(b).unwrap());
Ok(b.len())
})
.unwrap();
}
crl.perform().unwrap();
Ok(Box::new(Response {
resp: body.lock().unwrap().clone(),
headers: headers.lock().unwrap().clone(),
}))
}

最佳答案

关键错误似乎是这个:

error[E0597]: `body` does not live long enough
--> src/lib.rs:85:15
|
85 | resp: body.lock().unwrap().clone(),
| ^^^^ borrowed value does not live long enough
...
89 | }
| - `body` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created

headers 对象也是如此。

通过删除您的大量代码,我能够得到一个简化的复制器:

use std::sync::{Arc, Mutex};

pub struct Response {
resp: String,
headers: Vec<String>,
}

pub fn get(addr: &str) -> std::io::Result<Box<Response>> {
let headers: Vec<String> = Vec::with_capacity(10);
let headers = Arc::new(Mutex::new(headers));
let body = Arc::new(Mutex::new(String::with_capacity(1024)));
Ok(Box::new(Response {
resp: body.lock().unwrap().clone(),
headers: headers.lock().unwrap().clone(),
}))
}

我认为这与在最终 Ok(Box::new(...)) 返回值中构造的临时变量的生命周期有关。

我能够通过在外面拉锁/解包来让它编译。<​​/p>

let body = body.lock().unwrap();
let headers = headers.lock().unwrap();
Ok(Box::new(Response {
resp: body.clone(),
headers: headers.clone(),
}))

来自 Why do I get "does not live long enough" in a return value? 中给出的更全面的解释我发现你可以这样写

return Ok(Box::new(Response {
resp: body.lock().unwrap().clone(),
headers: headers.lock().unwrap().clone(),
}));

即添加显式 return 和尾随分号。虽然我有一种感觉 clippy 可能会说它的风格不好。

关于multithreading - 我如何装箱 Arc 和 Mutexed 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com