How do arc and mutex work?


how it work together?
And when are we use it ?
Should we use Mutex independent ?

I'm not entirely sure what you are asking, but you can use Arc<Mutex<T>>, and this is fairly common if you need reference counted mutable data, and performance isn't critical (shared mutable state can be a bottleneck at the hardware level if there are many writers).

You can also use Mutex<T> without Arc if you don't need reference count. I have done this several times when I had a mostly immutable struct shared with either Arc or just references (using scoped threads), but I had one mutable field in it.

Arc, Mutex, RwLock are probably fine for most programs, and most uses in most programs. But if you have a lot of writes to the same thing (including the reference count in an Arc!) that will eventually become a performance bottleneck as you scale up the number of CPU cores writing to the cache line in memory. So it is good to be aware that there are other ways such as RCU, hazard pointers, sharding etc.

1 Like

When you use scoped threads, &Mutex is sometimes useful. Arc<Mutex<T>> is the most common combination.

1 Like

(While that's a nice and useful diagram, the layouts of some of the types are implementation details. Mutex<T> no longer allocates on many (but not all) platforms.)

((But this isn't very relevant to your question.))

2 Likes

no, It's useful. maybe, what I really want to know is about experience or real life application in Arc and Mutex.

Thank for sharing

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.