如何打印由 Mutex
和 Arc
封装的 Vec
的值?我'm really new to Rust, so I'我不确定我是否正在措辞 .
这是我的代码,松散地基于文档 .
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错误:不匹配的类型:expected collections :: vec :: Vec <u8>,找到alloc :: arc :: Arc <std :: sync :: mutex :: Mutex <collections :: vec :: Vec <_ >>>(期望的struct collections :: vec :: Vec,找到struct alloc :: arc :: Arc)[E0308] datarace_fixed.rs:14 println!(“{ :?}“,String :: from_utf8(data).unwrap());
1 回答
要使用Mutex值,您必须锁定互斥锁,就像在生成的线程中一样 . (playpen):
注意String::from_utf8使用向量(为了将其包装在一个没有额外分配的字符串中),这很明显,它取值
vec: Vec<u8>
而不是引用 . 由于我们还没有准备好放弃我们对data
的控制,因此在使用此方法时我们必须clone
.更便宜的替代方案是使用from_utf8(playpen)的基于切片的版本: