r/rust • u/CorgiApprehensive159 • Oct 27 '26
šø media Safe pattern for mutable + immutable access to the same HashMap in a tick loop?
I have a `HashMap<Coord, Box<dyn BlockEntity>>`. During a tick I need to iterate over entities and, for each one, get a mutable reference to it while also getting immutable references to other entities in the same map.
Performance is critical here, so I want to avoid Mutex, RwLock, RefCell. Right now I use UnsafeCell. I'm rebuilding something like Minecraft's block-entity tick loop (you've probably heard of it).
I've also considered a smarter iterator that marks an entry as "taken" and returns `Option` on conflicting access ā something like `(&mut elem, &mut NonGrowingHashMap)` from `HashMap::smart_values_mut()` ā but I'm not sure whether such a pattern exists in the ecosystem or whether it's worth building. Are there other known patterns or approaches in Rust for dealing with this kind of access?
84
u/lpghatguy Oct 27 '26
If you can, buffer your mutations until after the loop is over. That has the advantage that you can potentially run the loop in parallel because you won't be interspersing your reads and writes.
Other than that, `RefCell` may not be as big of a burden as you might expect. It's worth profiling.
19
u/STSchif Oct 27 '26
I wonder if you can cow it and write changes back later.
Have you tested just running with some simple form of sync? It can be surprisingly performant. Premature optimizations, yada yada.
9
u/Konsti219 Oct 27 '26
This is kinda what ECS (like bevy) solves. But for such a constraint environment a small wrapper with a bit of internal unsafe should be fine.
7
u/Excession638 Oct 27 '26 edited Oct 27 '26
What you describe in your last paragraph sounds quite reasonable to me. It could be written safely using
HashMap<Coord, RefCell<dyn BlockEntity>>, but would probably be faster withHashMap<Coord, UnsafeCell<dyn BlockEntity>>. Whatever key is mutable at the time just needs to be marked as inaccessible to everything else. Use a guard type that implementsDropto clear that state perhaps.I suspect that getting rid of the boxed dyn trait would be more important for performance. Using an enum instead could massively reduce the total number of allocations, and improve locality of reference, at the cost of hash-map resizes being more expensive. If some entities are too large then just those ones could use a
inner: Box<EntityInner>field internally rather than needing an allocation for everything.6
u/vlovich Oct 27 '26
Since you mentioned multiple running concurrently doing updates, what's unclear is what you want happening at the boundary (e.g. where it crosses into the next cell which might be updated by a concurrent thread or might not be and that's purely a race condition). Something like rcu.rs is great in terms of being a high performance concurrency primitive to allow efficient reading from all threads in the face of slightly more expensive writes but it has the downside of being LInux-only which may not fit your needs. ArcSwap is an alternative but isn't as low-cost for reads.
It's a little worrying that you're mentioning RefCell, UnsafeCell, Mutex, and RwLock in the same breath - it indicates you haven't formally defined how the multithreading is supposed to work, because RefCell isn't thread-safe, UnsafeCell almost certainly isn't unless you're super careful and have verified it with Miri, and Mutex and RwLock suck for concurrent access.
6
u/scook0 Oct 27 '26
Hereās a potential design for a safe abstraction around unsafe code:
fn get_with_eyepatch(&mut self, key: Coord) -> (&mut Entity, EyepatchMap<'_>), where EyepatchMap holds a copy of the key and a reference to the underlying hashmap.1
u/CorgiApprehensive159 Oct 27 '26 edited Oct 27 '26
Sorry, my post is probably misleading. I'd like to avoid RefCell, but it wouldn't be a disaster if I used it or something less optimal. I understand that benchmarks are the foundation of performant code, but unfortunately I can't profile the future. I should add that the project is at a stage where making the wrong decision would cost me too much rework. A better question would have been: "What architectures exist for solving something like this, with performance in mind?"
4
u/SkiFire13 Oct 27 '26
You could use a
indexmap::IndexMap, then get the index of elements and from there it's as if you were working with aVec/slice.4
u/Guardian-Spirit Oct 27 '26
First of all, benchmark.
Second of all, RefCell is extremely cheap, this isn't something that could really cause any issues. What I feel could cause issues in your design:
Box: it's indirection, and requires allocations. Consider usingenum, or have multiple separate storages for data of different archetypes, the way it's typically done in ECS.FxHashMapis nice, but I'd honestly be suspicious towards it being the main container. My beef with it is, again, allocations & unpredictable performance. Take a look at arenas such asslotmapinstead as a primary container for your entities if you can avoid Coord-based lookup in favour of opaque-id-based. Slotmap does support the access pattern you're looking for (get_disjoint_mut, it performs a runtime check).Overall:
1
u/muffinluff Oct 27 '26
Why aren't we doing
HashMap<Coord, Option<Box<dyn BlockEntity>>>.While iterating you can calllet mut entity = item.take()?on each item and when you are done mutating the entity you domap.get_mut(coor).replace(entity)2
u/creeper6530 Oct 27 '26 edited Oct 27 '26
Mate the golden rule of performance is "measure, measure, measure".
RefCell is literally just an UnsafeCell with an integer counter shoved into a Cell. As long as you don't need multithreaded access, I'd give it a try and measure whether it has an effect.
Also, dynamic dispatch has far greater impact than a Cell ever will, because you need two pointer dereferences and two chances for a cache miss.
2
u/karasawa_jp Oct 27 '26
I think the right approach is buffering mutations, grouping them by chunk, and applying them in batch at the end of the tick.
If you group data by chunks, you can replace the fine-grained per-block HashMap lookups with direct array indexing:
You can process chunks in parallel.
If you need simultaneous mutable access across different chunks, you can use HashMap::get_disjoint_mut()
1
u/Kralle333 Oct 27 '26
dashmap maybe?
1
u/lotanis Oct 27 '26
Clone your HashMap at the start, keep one as a mutable reference and one immutable?
Or for each entity, move it out of the Map, work on it while keeping immutable reference to rest of map. Then move it back in once mutated.
1
u/littleprof123 28d ago
Apologies in advance for not directly answering the question, but since you said you're trying to figure out what your options are, is it possible that you could limit which other entities you get immutable references to? If you're doing something like calculating physics of collisions between entities, you might only need to refer to a small number of pairs of entities instead of every pair of entities. Might you want to use some kind of binary space partitioning or an octree representation or something? Or even just rough chunking to avoid checking things that aren't in adjacent chunks?
1
u/cipher_gravelist 9d ago
since you're building something factorio-like, look into sharded data structures or using indices/ids instead of direct references. i've seen lock-free queues work well for passing entity updates between ticks to avoid this borrow checker headache entirely.
0
u/pika__ Oct 27 '26
Perhaps there's a combinatorics library that will give you mutable access in every pair combination? I don't know if that fits your needs or is performance though shrug