2015-05-04 66 views
0

如何打印由MutexArc封装的Vec的值?我对Rust很新,所以我不确定我是否说得好。打印电弧和互斥锁类型

这是我的代码,松散地基于文档。

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

fn main() { 
    let data = Arc::new(Mutex::new(vec![104, 101, 108, 108, 111])); 

    for i in 0..2 { 
     let data = data.clone(); 
     thread::spawn(move || { 
      let mut data = data.lock().unwrap(); 
      data[i] += 1; 
     }); 
    } 

    println!("{:?}", String::from_utf8(data).unwrap()); 
    thread::sleep_ms(50); 
} 

编译器给我的错误:

$ rustc datarace_fixed.rs datarace_fixed.rs:14:37: 14:41 error: mismatched types: expected collections::vec::Vec<u8> , found alloc::arc::Arc<std::sync::mutex::Mutex<collections::vec::Vec<_>>> (expected struct collections::vec::Vec , found struct alloc::arc::Arc) [E0308] datarace_fixed.rs:14 println!("{:?}", String::from_utf8(data).unwrap());

回答

5

要与你锁定互斥,就像你在产生的线程做一个互斥值工作。 (playpen):

let data = data.lock().unwrap(); 
println!("{:?}", String::from_utf8(data.clone()).unwrap()); 

注意String::from_utf8消耗矢量(以包装在没有额外的分配一个字符串),这是显而易见的,从它取一个值vec: Vec<u8>而不是参考。由于我们还没有准备好放弃对data的持有,所以在使用此方法时我们必须使用clone

甲更便宜的替代将是使用的from_utf8的基于切片的版本(playpen):

let data = data.lock().unwrap(); 
println!("{:?}", from_utf8(&data).unwrap());