How can I print the values of a Vec
that is encapsulated by a Mutex
and Arc
? I'm really new to Rust, so I'm not sure if I am phrasing this well.
This is the code I have, loosely based on the documentation.
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);
}
The error that the compiler gives me:
$ rustc datarace_fixed.rs datarace_fixed.rs:14:37: 14:41 error: mismatched types: expected
collections::vec::Vec<u8>
, foundalloc::arc::Arc<std::sync::mutex::Mutex<collections::vec::Vec<_>>>
(expected structcollections::vec::Vec
, found structalloc::arc::Arc
) [E0308] datarace_fixed.rs:14 println!("{:?}", String::from_utf8(data).unwrap());