Mass Battle Frameworkv1.20.0

Mass Entity 上的线程安全 Thread Safety on Mass Entity

MEMORY & THREAD SAFETY

能并行的、不能并行的、以及三类最容易写错的东西 · 2026-11-22What parallelises, what cannot, and the three ways it usually goes wrong · 2026-11-22

系列这些文章写给人和他的 agent 一起看。这套文档怎么读 →SeriesThese posts are for you and your agent. How to read these docs →

先把边界说准:写数据可以并行,动结构不行 The Boundary, Stated Precisely

很多人会把它总结成一条很干脆的规则:"UObject 不能在并行里碰"。这话听着对,其实是错的,而且信了它还会把本来能并行的东西也搬出去。我们自己的渲染路径就是反例:逐实体、逐槽位往渲染批次的数据里写,我们明确当成并行安全来做,而那也是在写 UObject 的数据。Niagara 要读的数组一样。

It is tempting to boil this down to one tidy rule: "you cannot touch a UObject in parallel". It sounds right. It is wrong, and believing it also pushes out work that was fine in parallel. Our own render path is the counter-example: per-entity, per-slot writes into render batch data run in parallel and we label them parallel-safe, and that is still writing into a UObject's data. The arrays Niagara reads are no different.

并行里安全Safe in a wave必须串行Must be serial
往一块数据里写:片段、批次槽位、Niagara 读的数组、自己线程的临时缓冲。写进去就完了,引擎那边没有结构跟着变Writing into a buffer: fragments, batch slots, the arrays Niagara reads, your own thread's scratch. You write and that is the end of it — no engine structure moves 改场景对象的变换或挂接:SetActorTransform、SetWorldLocationAndRotation、SetWorldTransformChanging a scene object's transform or attachment: SetActorTransform, SetWorldLocationAndRotation, SetWorldTransform
纯计算:插值、求交、路径、伤害、避障Pure computation: interpolation, intersection, paths, damage, avoidance 创建与销毁:UObject 的 Spawn / Destroy,实体的生成与回收Creation and destruction: spawning or destroying a UObject, spawning or recycling an entity
把"要做的事"记到自己线程的缓冲里Recording what you want to do into your own thread's buffer 改原型:加/减 tag、加/减 fragment。它会让实体搬家、换块Changing the archetype: add or remove a tag or fragment. That moves the entity to another chunk
只读一个在本波之前就已经写好的副本Reading a copy that was finished before this wave 改共享容器:往 TMap 里增删键、改结构本身Mutating a shared container: inserting or removing keys in a TMap

说到底就一句:写数据可以并行,动结构必须串行。这里说的"结构",是引擎和 Mass 替世界维护的那套东西:场景登记与空间结构、原型表、块的归属、共享容器本身。并行去改它,等于几个线程同时改一棵树。

The short version: writing data parallelises, moving structure does not. "Structure" means what the engine and Mass maintain about the world: scene registration and the spatial structure, the archetype table, chunk ownership, the containers themselves. Change it from several threads at once and they are all editing the same tree.

结构变动的唯一出口:Defer The Only Exit for Structural Change: Defer

"改原型"这件事,连收集器都轮不到你自己写,必须走引擎的延迟命令。MassEntity 提供 Defer():加 tag、减 tag、加 fragment、减 fragment、销毁实体,全是把命令排进队列,到阶段边界一起落地。

"Change the archetype" does not even belong in your own code. It has to go through the engine's deferred commands. MassEntity gives you Defer(): add tag, remove tag, add fragment, remove fragment, destroy entity, they all queue a command that lands at the stage boundary.

这套写法在我们代码里到处都是:Behavior 里加/减 FAppearingTag,Reaction 里加 FDyingTag,Host 里给收编的目标打死亡标记,每一处都是 Context.Defer().AddTag<...>(Entity)。并行循环里没有一处直接改实体结构。

It shows up everywhere in our code: adding and removing FAppearingTag in Behaviour, adding FDyingTag in Reaction, marking an inherited target for death in Host. Every one is Context.Defer().AddTag<...>(Entity). No parallel loop restructures an entity directly.

这和"阶段边界"是同一件事的两面:延迟命令在阶段边界冲刷,所以这一帧生成的实体,下一段才查得到。生成、销毁、换原型都走这条出口。这几种操作放在并行里做就是错的,跟慢不慢没关系。

Same fact as the stage boundary, seen from the other side: deferred commands flush there, which is why entities spawned this frame become visible only to the next stage. Spawning, destruction and archetype change all take that exit. Inside a wave these operations are wrong; speed has nothing to do with it.

UObject:哪些调用能并行 UObjects: Which Calls Actually Parallelise

真正不能并行的是会去改场景的调用。我们为这一类专门写了个操作类型:FCpuInterpUObjectOp(实体 + 类型 + 世界变换),头文件一句话把原因说清:Actor 的 SetActorTransform、音效的 SetWorldLocationAndRotation、非合批特效的 SetWorldTransform 都是 UObject 调用,只能游戏线程做。

What really cannot parallelise is calls that go and move the scene. We wrote a dedicated op type for those: FCpuInterpUObjectOp (entity, kind, world transform). The header states the reason in one line — the actor's SetActorTransform, the sound's SetWorldLocationAndRotation, the unbatched effect's SetWorldTransform are UObject calls, so they are game-thread only.

形状还是那套:并行段把变换算好,塞进 FParallelGatherer,Merge() 之后在末尾逐条调用。同一个处理器里,插值数学和片段写入留在并行段(标"并行安全"),SetNiagaraArray* 这种把数据推给组件的调用,用脏标志延迟到串行段。

The shape is familiar: the parallel pass computes transforms and pushes them into a FParallelGatherer; after Merge() the tail calls them one by one. In the same processor, the interpolation math and fragment writes stay in the parallel pass (labelled parallel-safe), while a call like SetNiagaraArray*, which pushes data into the component, waits for the serial phase behind a dirty flag.

至于为什么位移必须串行,我只能给个推测:引擎维护着"这个对象注册在场景的哪条路径、在空间结构的哪一层、包围盒挂在哪个节点",位移要动这套东西,并行改就等于同时重建那棵树。推测归推测,能落地的结论是稳的:按写数据和改结构这两类去分。

As for why transforms must be serial, I can only offer a guess: the engine keeps track of which scene path an object is registered at, which level of the spatial structure it sits in, which node holds its bounds. A transform moves all of that, so concurrent changes rebuild the same tree at once. Guess aside, the practical rule holds: sort every call into writing data or moving structure.

最隐蔽的一类:跨实体读 The Subtlest One: Cross-Entity Reads

前面几类会崩,这一类不崩也不报错,只是结果不稳,所以最难查。判据很具体:同一个遍历里,一个片段字段既被主人写,又被别人跨读。读到的值就取决于目标先跑还是后跑,同一份代码能跑出两个答案。

The earlier ones crash. This one does not crash and says nothing; it just hands back unstable answers, which makes it the hardest to find. The criterion is concrete: inside one traversal, a fragment field is written by its owner and cross-read by someone else. What you read then depends on whether the target ran first or later. Same code, two answers.

注意范围是遍历,跟有没有开并行无关。你把某个处理器的并行关掉、退成串行遍历,只要两端的数组顺序不同(比如一端是重同步后按 (EntityType, UniqueID) 重建的,另一端保留历史顺序),同一对实体照样可能被以相反的顺序访问,读出不同的值。

The scope is the traversal, not whether the loop runs in parallel. Force a processor's parallelism off and the risk remains: if the two peers order their arrays differently, say one rebuilt by (EntityType, UniqueID) after a resync while the other kept historical order, the same pair can still be visited in the opposite order and the read forks.

解法只有一个方向:去读一份在本波之前就写完的副本。线上在用的有四种:

The fix only goes one way: read a copy that was finished before this wave. Four are in live use:

副本The copy谁在什么时候写它Written by, and when
FLocating::PreLocation / FRotating::PreRotationQuatFLocating::PreLocation / FRotating::PreRotationQuat 网格更新处理器在帧首、自己的波里逐实体自写;那趟波在移动波之前就结束了The grid update processor, frame start, a per-entity self-write inside its own wave, which finishes before the move wave
FTracing::TargetLocation 及同族字段FTracing::TargetLocation and its siblings 索敌处理器在循环开头、以及每次重新捕获目标时刷新The trace processor, at loop top and at every acquisition site
网格里那份 64 字节的每单位记录The 64-byte per-agent record in the hash grid 帧首网格注册时写入——这也是移动从不解引用邻居片段的原因Written at frame-start grid registration — which is why move never dereferences a neighbour's fragment
FParallelGatherer + 串行排序冲刷FParallelGatherer with a sorted serial flush 任何"一趟波要向别的实体发布"的东西Anything a wave has to publish to other entities

一份副本要算"稳定",得同时满足两条:(一)它的写入波在两端都早于消费方;(二)那次写入本身与顺序无关(逐实体自写,或者串行排序后写)。在消费那一趟里现刷的缓存,两条都不满足,我们就踩过这个坑。

A copy counts as stable only when (a) its writing pass finished before the consumer on both peers and (b) the write itself is order-independent, either a per-entity self-write or a sorted serial one. A cache refreshed inside the consuming wave satisfies neither. We have walked into that one.

测试上还有个陷阱。我们给每处并行都编了号(MBParallelFor<MBParallelToggle::...>),调试时可以强制全部单线程。但单线程跑绿了说明不了什么:它消掉的是调度抖动,不是顺序依赖。真有 bug,重同步之后照样分叉。

There is a testing trap as well. Every parallel region carries a name (MBParallelFor<MBParallelToggle::...>) and can be forced single-threaded while debugging. A green run under that proves nothing. It removes scheduling jitter, not order dependence. If the bug is real, it still forks after a resync.

片段引用什么时候失效 When a Fragment Reference Dies

规则只有一条,后果有两个:从 GetFragmentPtr / GetFragmentRef 拿到的指针,一直有效到"有一次原型变更真的执行了"为止。在指针上写字段是正常用法,永远不会让它失效,写数据不搬家。

One rule, two consequences: a pointer from GetFragmentPtr / GetFragmentRef stays valid until an archetype change actually executes. Writing fields through it is normal use and never kills it; writing data does not move anything.

后果一:Defer() 还没执行,指针此刻仍然有效。迁移发生在阶段边界,不是你排命令的那一刻。这也解释了为什么"加了 tag 再改值"有时候看着还能用:它还没搬。

One: the deferred command has not run yet, so the pointer is still valid right now. The migration happens at the stage boundary, not when you queued it. That is also why "add a tag, then write through the old pointer" sometimes appears to work. It has not moved yet.

后果二:生成宿主会在循环里把块重新排一遍。SpawnActorHost / SpawnFxHost / SpawnSoundHost 走的是延迟创建,可能在循环中途重排块。所以"边遍历边生成"的循环里,要么每次迭代重新取引用,要么只把 POD 值带过那次调用:

Two: a spawn host can reorganise chunks in the middle of your loop. SpawnActorHost / SpawnFxHost / SpawnSoundHost use deferred creation, which may reorganise chunks mid-loop. So in a loop that spawns while it iterates, re-fetch every iteration, or carry only POD values across the call:

别把"每次迭代重取"当成能优化掉的冗余,重取本身就是修复。这和上一篇"片段指针只活一次"是同一件事,只是这里触发的原因是生成。

Do not file the per-iteration refetch under waste to optimise away. The refetch is the fix. Same fact as "a fragment pointer lives for one use" in the previous post; here the cause is spawning rather than a tag.

另一半也在这里说清:跨实体写(A 改 B 的片段)不归这一类管。改值不动原型也不动结构,所以不算禁忌,只要求每个目标恰好一个写者(A 写 B、B 写 C、C 写回 A 可以,要的是"函数",不是"无环")。真致命的是两个写者落到同一个目标,最后留下谁的值看调度;并行循环里所有实体跑同一段逻辑,这种多对一几乎马上出现。所以实战规矩是:点不出那个唯一写者,就走收集器。

The other half belongs here. Cross-entity writes (A mutating B's fragment) are not in this class. A value write moves no archetype and no structure, so it is not forbidden, as long as each target has exactly one writer. A writes B, B writes C, C writes back to A, all fine; what is required is a function, not an acyclic graph. What does kill it is two writers on one target: whichever the scheduler ran last wins. And since a parallel loop runs the same logic for every entity, that many-to-one shape shows up almost at once. So in practice: if you cannot name the sole writer, go through a gatherer.

自己那块内存:thread_local 暂存 Your Own Memory: Thread-Local Scratch

并行循环里最大的一笔开销经常是每实体一次分配。所以块头大一点的工作状态,用 static thread_local 声明在 lambda 里、chunk 循环之前:每个线程分配一次,后面所有块复用。判据也清楚:超过 1 KB、每实体复用,用暂存上下文;不到 1 KB、单次用完的 POD,放栈上;跨帧属于实体,进片段;所有实体共享,用共享片段或子系统字段。

The largest cost in a parallel loop is often one allocation per entity. So bulky working state goes into a static thread_local in the lambda body, ahead of the chunk loop: allocated once per thread, reused by every chunk after. The rules are plain: over 1 KB and reused per entity, use a scratch context; under 1 KB and single-use POD, a stack variable; tied to an entity across frames, a fragment; shared by everything, a shared fragment or a subsystem field.

三条使用纪律。每实体开始时 Reset,不要重新分配,同时 Reserve 一个合理上限,别让缓冲无界增长。热的邻居数组用 TInlineAllocator<N>,前 N 个留在栈附近,稀疏人群里不用来回堆分配。事件数组是例外:它不按实体清空,块内一直累积,到块末再刷进全局收集器。

Three rules of use. Reset at the start of each entity instead of reallocating, and Reserve a sane cap so a buffer cannot grow without bound. Hot neighbour arrays get a TInlineAllocator<N>, so the first N stay inline and sparse crowds stop round-tripping to the heap. Event arrays are the exception: they accumulate across the chunk instead of clearing per entity, and flush into the global gatherer at its end.

共享容器:TMap 只能在游戏线程改 Shared Containers: TMaps Are Game-Thread Only

"外层 TMap + 每块一份密集数组"是稀疏空间结构的固定写法:外层覆盖无界世界,内存跟着活动走,内层连续好读。这套写法带着一条硬规则:并行波绝不往 TMap 里插或删。块的创建和销毁只走串行路径,网格那边靠命令冲刷兜底,压力场那边在收集器合并后的串行段预创建。

An outer TMap of blocks with a dense array per block is the fixed shape for sparse space: the outer layer covers an unbounded world, memory follows activity, the inner layer is contiguous. It comes with one hard rule: a parallel wave never inserts into or removes from the TMap. Blocks are created and destroyed on serial paths only, through the command flush for the grid and through pre-creation in the merged serial pass for the pressure field.

调试绘制也归同一条规则管:不要在 task 或处理器里直接调 DrawDebugXxx,全部走子系统的绘制队列,由串行段统一派发。理由和上面一样:它是引擎调用,而它要读的数据正在并行段里被写。

Debug drawing falls under the same rule: never call DrawDebugXxx from task or processor code. Everything goes through the subsystem's draw queue, dispatched in the serial section, for the same reason: it is an engine call, and the data it would read is being written in the parallel pass.

排序键:实体句柄的 Index 不能当键 Sort Keys: Never the Entity Handle Index

这条看着像"确定性"的要求,其实也算线程安全:并行出来的结果顺序不定,你得用一个两端都稳定的键把它规范回去。这个键只能是 UniqueID,不能是实体句柄里的 Index。

This looks like a determinism requirement and it is also a thread-safety one: parallel work produces results in no particular order, and you have to normalise them with a key both peers share. That key is UniqueID, never the Index inside the entity handle.

原因是重同步。客户端恢复时按 (EntityType, UniqueID) 重建实体,它那边的句柄 Index 顺序就等于 UID 顺序;服务器从不恢复,Index 还是历史创建顺序。同一批实体,两端的 Index 相对顺序不同。任何按 Entity.Index 排的队列,恢复之后都排出不同结果,于是池顺序、处理顺序分叉,哈希分叉,再触发一次恢复。这个坑我们踩过,修的时候做绝了:Index 连"平局裁决"都不许当,哪怕主键唯一、理论上永远触发不到。

The cause is resync. On recovery the client rebuilds entities in (EntityType, UniqueID) order, so its handle Index order matches UID order. The server never restores and keeps historical creation order. So the same set of entities has a different relative Index order on the two peers. Any queue sorted by Entity.Index sorts differently after recovery, and from there pool order, processing order and the hash diverge, which triggers another recovery. We have been here, and the fix was made absolute: Index is not allowed even as a tiebreaker, even when the primary key is unique and it provably never fires.

排序也不是每帧都付。SortByUniqueID 第一行就是 if (bDeterministic),不需要逐帧一致的模式直接跳过。这笔代价只为"两端同一结果"付。

The sort is not paid unconditionally either. The first line of SortByUniqueID is if (bDeterministic); modes that do not need frame agreement skip the whole thing. The cost buys agreement between peers.

为什么不是加锁 Why Not Just Lock

肯定会有人问:不就是多个线程往一个地方写吗,加把锁不就完了。两个原因。先说性能:一帧几千次生成,每次都抢同一把锁,并行度会掉到接近串行,锁本身还要付钱。再说后一个:锁只保证不崩,保证不了顺序。谁先抢到锁还是调度说了算,你照样拿不到可复现的顺序,只是把数据竞争换成了顺序竞争。

Someone always asks: it is just several threads writing to one place, why not a lock. Two reasons. Performance first: thousands of spawns a frame fighting over one lock drops parallelism to roughly serial, and you still pay for the lock. The deeper reason: a lock guarantees no crash, not an order. Who gets it first is still up to the scheduler, so you still have no reproducible sequence. You have traded a data race for an ordering race.

收集器的代价有界,也量得出来:每线程一个缓冲(按实际到达的线程数分配,没到过的槽不花钱)、合并时拷一次、排序 O(n log n)。三笔都随数据量涨,不随争用涨。加锁的代价随线程数变坏。一个跟着数据量走,一个跟着并行度走,区别就在这儿。

A gatherer's cost is bounded and measurable: one buffer per thread, sized by the threads that actually arrived, unused slots free; one copy at merge; one O(n log n) sort. All three grow with the data, not with contention. A lock's cost grows with thread count. One follows the item count, the other follows parallelism, and that is the difference.

检查单 The Checklist

写处理器的时候,逐条过一遍:

Run through this list when you write a processor:

一、这一行写的是数据还是结构?写片段、写批次槽位、写 Niagara 读的数组,是数据,留着。二、这一行调的是不是会改场景的引擎 API?设变换、改挂接、创建、销毁,收集起来串行做。三、这一行会让新东西存在吗?生成实体、生成投射物、创建特效,走 Defer()。四、我在跨读别人的字段吗?那它必须是本波之前就写完的副本,而且那次写入本身与顺序无关。五、我手里这个引用跨过一次生成调用吗?跨了就重新取。六、我往共享容器里插删了吗?插删只能在串行段。七、这个队列的排序键里出现句柄 Index 了吗?出现就是错的。

One: is this line writing data or structure? Fragments, batch slots, the arrays Niagara reads, that is data, leave it alone. Two: does this line call an engine API that moves the scene? Setting a transform, changing an attachment, creating, destroying, gather it for the serial section. Three: does this line make something new exist? Spawning an entity, a projectile, an effect, go through Defer(). Four: am I cross-reading someone else's field? Then it has to be a copy finished before this wave, and that write has to be order-independent. Five: did this reference survive a spawn call? If so, fetch it again. Six: am I inserting or removing in a shared container? That belongs in the serial section. Seven: does any sort key contain a handle Index? Then it is wrong.

最后提一句:这条边界是试出来的。哪些写入安全,取决于引擎内部那一刻在维护什么;同一个类型里,有的调用能并行,有的不能。所以每加一处并行写,你都得说清"它只碰数据",不能说"它是个 UObject,但应该没事"。

One last thing: this boundary is found, not memorised. Which writes are safe depends on what the engine is maintaining at that moment. Within a single type, some calls parallelise and some do not. So every parallel write you add needs a reason of the form "this touches data only", never "it is a UObject but it is probably fine".

一句话 In One Line

并行里只写数据,要动结构的收集起来串行做,跨实体只读本波之前写好的副本。结构变动走 Defer(),位移走收集器,跨实体读走上一帧的副本,排序键只用 UniqueID。这四条守住,并行才安全,加锁替代不了其中任何一条。

In a wave, write data only, gather anything that moves structure for the serial part, and read only copies finished before the wave. Structural change goes through Defer(), transforms through a gatherer, cross-entity reads through a previous-frame copy, sort keys through UniqueID alone. Hold all four and parallelism is safe. No lock stands in for any of them.

Leroy Works · Mass Battle Framework 作者
联系:Discord · QQ 群 916358710 · Fab · 全部联系方式

Leroy Works — author of Mass Battle Framework
Contact: Discord · QQ group 916358710 · Fab · all channels