4 ms·
From 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 Objec
by sesm 2y ago
From 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!