5 ms·
Ok, so do I understand correctly that Arc<MyType> would be read-only, and for write access I'll have to use Arc<Mutex<MyType>> or Arc<RwLock<MyType>>? So what a
by sesm 2y ago
Ok, so do I understand correctly that Arc<MyType> would be read-only, and for write access I'll have to use Arc<Mutex<MyType>> or Arc<RwLock<MyType>>? So what about Mutex and RwLock, do they have any static checks associated with them? Do they introduce an extra layer of pointer indirection, or Rust resolves Arc<Mutex> and Arc<RwLock> to 2 different implementations with only 1 layer of indirection?
- remram 2y agoThe extra static checks are the mutable vs non-mutable references, and the Sync/Send traits. Mutex does not introduce indirection.
- sesm 2y agoFrom Rust official docs: `let lock = Arc::new(Mutex::new(0_u32));` Doesn't this mean that Mutex introduces one more pointer? For example, in Java every Object has a built-in mutex, adding some memory overhead in order to remove one extra layer of pointer dereferencing. As far as I understand, Rust introduces an extra layer of pointer indirection with Mutex, which can hurt performance significantly with cache misses.
- kbolino 2y agoIt is only Arc and not Mutex that allocates and thus has "extra" pointer indirection. A Mutex can live perfectly well on the stack, as long as it outlives the threads accessing it. Arc has to allocate, because it is meant to outlive the function that created it, and the only place to safely do that is on the heap.
- deleted 2y ago[deleted]
- oasisaimlessly 2y ago> Doesn't this mean that Mutex introduces one more pointer? No. That syntax is roughly equivalent to the following C++: auto const lock = std::make_shared<std::pair<std::mutex, uint32_t>>( std::piecewise_construct, std::make_tuple(), std::make_tuple(0));
- sesm 2y agoThanks, that's the best explanation!
- dannymi 2y agoI would suggest you read the source code of Mutex <https://doc.rust-lang.org/src/std/sync/mutex.rs.html#178-182 https://doc.rust-lang.org/src/std/sync/mutex.rs.html#178-182> and then of UnsafeCell <https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html>. So, the layout of Mutex<T> is the same as T and then some lock (well, obviously). >Rust introduces an extra layer of pointer indirection with Mutex, which can hurt performance significantly with cache misses. Why would there be an extra pointer dereference? There isn't.
- sesm 2y agoThanks for the explanation!