swizard
swizard

Reputation: 2701

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.

  1. If I want to share my data between several threads immutably, I'll use Arc<T>.
  2. 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:

What is the right effective solution then?

Upvotes: 3

Views: 2438

Answers (2)

Pascal Pixel Rigaux
Pascal Pixel Rigaux

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

swizard
swizard

Reputation: 2701

A std::sync::RwLock is what I am looking for, thanks @Shepmaster!

Upvotes: 5

Related Questions