I try to find a way to share a Mutex with multiple threads like Arc<Mutex> but without allocation the Mutex on the heap.
The solution provided in the Rust book is to allocate the Mutex on the heap with Arc<Mutex> but this is not satisfying. I know that the Mutex is still alive after thread ends and I don't want to do extra heap allocation jsut to satisfy the borrow checker.
This should not be a problem :
let counter = Mutex::new(0);
{
let mut handles = vec![];
for _ in 0..10{
let handle = thread::spawn(||{
let mut scoped = counter.lock().unwrap();
*scoped += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
} // All Threads are done here, even handles.
println!("{}", counter.lock().unwrap()); // Doing this should be done without any problem
It doesn't really make sense to have reference-counting for something on the stack. You would need to use lifetimes to ensure that the clones don't outlive the stack memory it is stored in, but once you are using lifetimes, you don't also need the reference counting.