How do I share data between several threads when I need it mutable only rarely?
I have some data of type T
which implements neither Copy
nor Clone
.
- If I want to share my data between several threads immutably, I'll use
Arc<T>
. - If I want to share it mutably, I'll use
Arc<Mutex<T>>
.
What if I want to share it first mutably, and then immutably in a loop? So:
- I cannot use either
Arc<T>
orArc<Mutex<Arc<T>>>
because I will not be able to mutate the data in the "mutable" threads. - I can use
Arc<Mutex<T>>
, but then I have tolock()
it in each of the "immutable" threads to reachT
, losing parallelism. - I cannot copy data after mutation is complete, because it is expensive (or there is no way to implement
Clone
).
What is the right effective solution then?
A std::sync::RwLock
is what I am looking for, thanks @Shepmaster!