2015-05-04 64 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());