Improve thread safety and performance in core systems

Refactors event, entity, and physics management to use thread-safe and lock-free data structures (Immutable collections, ConcurrentQueue, ConcurrentDictionary, Channel) for improved concurrency and performance. Replaces O(n) queue lookups with O(1) set/dictionary checks, ensures atomic updates for shared state, and optimizes queue draining and deferred action processing. Updates related code to use new APIs and patterns, and adds documentation for thread safety and workflow.
This commit is contained in:
Eero
2025-12-29 16:47:10 +08:00
parent e167a34f32
commit 7b8275100d
17 changed files with 368 additions and 191 deletions
@@ -64,6 +64,32 @@ namespace Barotrauma.Networking
// key = entity, value = NetTime.Now when sending
public readonly Dictionary<Entity, float> PositionUpdateLastSent = new Dictionary<Entity, float>();
public readonly Queue<Entity> PendingPositionUpdates = new Queue<Entity>();
private readonly HashSet<Entity> pendingPositionUpdatesSet = new HashSet<Entity>();
/// <summary>
/// Attempts to enqueue a position update for the given entity. Returns true if the entity was added, false if it was already in the queue.
/// Uses HashSet for O(1) lookup instead of Queue.Contains() which is O(n).
/// </summary>
public bool TryEnqueuePositionUpdate(Entity entity)
{
if (pendingPositionUpdatesSet.Add(entity))
{
PendingPositionUpdates.Enqueue(entity);
return true;
}
return false;
}
/// <summary>
/// Dequeues a position update and removes it from the HashSet tracking.
/// </summary>
public Entity DequeuePositionUpdate()
{
if (PendingPositionUpdates.Count == 0) { return null; }
var entity = PendingPositionUpdates.Dequeue();
pendingPositionUpdatesSet.Remove(entity);
return entity;
}
public bool ReadyToStart;
@@ -353,6 +379,7 @@ namespace Barotrauma.Networking
{
NeedsMidRoundSync = false;
PendingPositionUpdates.Clear();
pendingPositionUpdatesSet.Clear();
EntityEventLastSent.Clear();
LastSentEntityEventID = 0;
LastRecvEntityEventID = 0;