繁体   English   中英

"如何在线程之间传递包含 String 引用的结构?"

[英]How do you pass a struct that contains a String reference between threads?

在下面的代码片段中,我试图创建一个包含字符串值的元组和一个包含属性的结构,该属性设置为对元组中第一个值的引用。
我的问题是如何使字符串的寿命足够长。

这是代码:

#[derive(Debug, Clone)]
struct RefTestStruct {
    key: usize,
    ref_value: Option<&'static str>,
}

fn init3<'a>( cache: &Arc<Mutex<HashMap<usize, (String, Option<RefTestStruct>)>>> ) {
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        //create reference copy of cache
        let cache_clone = Arc::clone(cache);

        let handle = thread::spawn(move || {
                //lock cache
                let mut locked_cache = cache_clone.lock().unwrap();

                // add new object to cache
                let tuple_value = (format!("value: {}", idx), None );
                let mut ts_obj = 
                    RefTestStruct {
                        key: idx,
                        ref_value: Some( tuple_value.0.as_str() ),
                    };
                tuple_value.1 = Some(ts_obj);
                locked_cache.insert(idx as usize, tuple_value);
    
                println!("IDX: {} - CACHE: {:?}", idx, locked_cache.get( &(idx as usize) ).unwrap() )
            });

        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("\n");
}

fn main() {
    // init
    let cache = HashMap::<usize, (String, Option<RefTestStruct>)>::new();
    let am_cache = Arc::new(Mutex::new(cache));

    init3(&am_cache);

    // change cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
                let mut locked_cache = cache_clone.lock().unwrap();
                let tuple_value = locked_cache.get_mut( &(idx as usize) ).unwrap();
                (*tuple_value).0 = format!("changed value: {}", (*tuple_value).1.unwrap().key + 11);
                let ts_obj = 
                    RefTestStruct {
                        key: (*tuple_value).1.unwrap().key,
                        ref_value: Some( (*tuple_value).0.as_str() ),
                    };
                tuple_value.1 = Some(ts_obj);

                // locked_cache.insert(idx as usize, tuple_value);

            });
        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

    // display cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
                let locked_cache = cache_clone.lock().unwrap();
                let ts_obj = locked_cache.get( &(idx as usize) ).unwrap();

                println!("IDX: {} - CACHE: {:?}", idx, &ts_obj );

            });
        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

}

错误:

错误[E0597]: tuple_value.0寿命不够长 --> src\\main.rs:215:42 | 215 | ref_value: 一些( tuple_value.0.as_str() ), | ^^^^^^^^^^^^^^^^^^^^^^ | | | 借来的价值活得不够长| 参数要求为'static ... 221 | 借用tuple_value.0 }); | - tuple_value.0在仍然被借用的时候掉到了这里

struct RefTestStruct {
    key: usize,
    ref_value: Option<&'static str>,
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM