gpt4 book ai didi

rust - `RefCell` 不能在线程之间安全地共享?

转载 作者:行者123 更新时间:2023-12-04 01:02:14 25 4
gpt4 key购买 nike

这是 How to re-use a value from the outer scope inside a closure in Rust? 的延续,打开新的 Q 以获得更好的演示。

// main.rs

// The value will be modified eventually inside `main`
// and a http request should respond with whatever "current" value it holds.
let mut test_for_closure :Arc<RefCell<String>> = Arc::new(RefCell::from("Foo".to_string()));

// ...

// Handler for HTTP requests
// From https://docs.rs/hyper/0.14.8/hyper/service/fn.service_fn.html
let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(|req: Request<Body>| async move {
if req.version() == Version::HTTP_11 {
let foo:String = *test_for_closure.borrow();
Ok(Response::new(Body::from(foo.as_str())))
} else {
Err("not HTTP/1.1, abort connection")
}
}))
});

不幸的是,我收到 RefCell<std::string::String> cannot be shared between threads safely :
enter image description here

最佳答案

RefCell 仅适用于单线程。您将需要使用类似但适用于多个线程的互斥锁。你可以在这里阅读更多关于互斥锁的信息:https://doc.rust-lang.org/std/sync/struct.Mutex.html .
这是将 Arc > 移动到闭包中的示例:

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

fn main() {
let mut test: Arc<Mutex<String>> = Arc::new(Mutex::from("Foo".to_string()));

let mut test_for_closure = Arc::clone(&test);
let closure = || async move {
// lock it so it cant be used in other threads
let foo = test_for_closure.lock().unwrap();
println!("{}", foo);
};
}

关于rust - `RefCell<std::string::String>` 不能在线程之间安全地共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67877287/

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