The following code in which a struct Counter wraps a u32. I am using Arc to wrap and Mutex to allow safe and shared access to the value. I have omitted the threaded code to provide a simple example:
use std::sync::{Arc, Mutex};
fn main() {
#[derive(Debug)]
struct Counter {
count: u32,
}
let counter = Arc::new(Mutex::new(Counter { count: 0 }));
for _ in 0..10 {
let mut c_int = counter.lock().unwrap();
c_int.count += 1;
}
println!("{:?}", counter.lock().unwrap());
}
Here counter.lock().unwrap() is able to transparently lock the mutex and unwrap the result and I don't need to dereference the Arc. Also dereference on c_int works transparently.
Consider following code where Counter is replaces with u32:
use std::sync::{Arc, Mutex};
fn main() {
let counter = Arc::new(Mutex::new(32));
for _ in 0..10 {
let mut c_int = counter.lock().unwrap();
c_int += 1;
}
println!("{:?}", counter.lock().unwrap());
}
It wouldn't compile because c_int += 1 is not valid as it doesn't derefernces to u32.
My questions are:
Why structs are special while primitives are not while using through a smart pointer like
Mutex?How I can use functions of
Mutexdirectly on anArc?
I think both have to do with Deref but not sure how.