`RefCell<std::string::String>`不能在线程之间安全地共享? [英] `RefCell<std::string::String>` cannot be shared between threads safely?

查看:69
本文介绍了`RefCell<std::string::String>`不能在线程之间安全地共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是

解决方案

RefCell 仅适用于单线程.您将需要使用类似但适用于多个线程的互斥锁.您可以在此处阅读有关互斥锁的更多信息:https://doc.rust-lang.org/std/sync/struct.Mutex.html.

以下是移动 Arc> 的示例.进入一个闭包:

use std::sync::{Arc, Mutex};fn 主(){让 mut 测试:Arc>= Arc::new(Mutex::from(Foo".to_string()));让 mut test_for_closure = Arc::clone(&test);让闭包 = ||异步移动{//锁定它,使其不能在其他线程中使用让 foo = test_for_closure.lock().unwrap();println!("{}", foo);};}

This is a continuation of How to re-use a value from the outer scope inside a closure in Rust? , opened new Q for better presentation.

// 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")
            }
        }))
    });

Unfortunately, I get RefCell<std::string::String> cannot be shared between threads safely:

解决方案

RefCell only works on single threads. You will need to use Mutex which is similar but works on multiple threads. You can read more about Mutex here: https://doc.rust-lang.org/std/sync/struct.Mutex.html.

Here is an example of moving an Arc<Mutex<>> into a closure:

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);
    };
}

这篇关于`RefCell&lt;std::string::String&gt;`不能在线程之间安全地共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆