Reputation: 2701
I have some data of type T
which implements neither Copy
nor Clone
.
Arc<T>
.Arc<Mutex<T>>
.What if I want to share it first mutably, and then immutably in a loop? So:
Arc<T>
or Arc<Mutex<Arc<T>>>
because I will not be able to mutate the data in the "mutable" threads.Arc<Mutex<T>>
, but then I have to lock()
it in each of the "immutable" threads to reach T
, losing parallelism.Clone
).What is the right effective solution then?
Upvotes: 3
Views: 2438
Reputation: 702
For some use-cases (cache for example), Arc<Mutex<Arc<T>>>
is an interesting solution.
The main difference with RwLock
: you can get the value and use it without keeping the read lock.
fn get<T>(mutex: &Arc<Mutex<Arc<T>>>) -> Arc<T> {
mutex.lock().unwrap().clone()
}
Full example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2a2db2cd8aebf6a246486679f841827a
Upvotes: 0