Skip to content

Commit

Permalink
Fix thread-safety problem in World.WordSize by applying Interlocked o…
Browse files Browse the repository at this point in the history
…perations
  • Loading branch information
penspanic committed Jan 11, 2025
1 parent 804423a commit 0c78c92
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
43 changes: 43 additions & 0 deletions src/Arch.Tests/MultiThreadTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Arch.Core;
using static NUnit.Framework.Assert;

namespace Arch.Tests;

[TestFixture]
public class MultiThreadTest
{
/// <summary>
/// Checks if the <see cref="World.WorldSize"/> is correct when creating World multithreaded.
/// </summary>
[Test]
public void MultiThreadedCreateAndDestroy()
{
int originalWorldSize = World.WorldSize;
const int testCount = 10;
for (int i = 0; i < testCount; ++i)
{
var threads = new List<Thread>();
for (var j = 0; j < Environment.ProcessorCount; j++)
{
var thread = new Thread(() =>
{
for (var j = 0; j < 1000; j++)
{
var world = World.Create();
World.Destroy(world);
}
});
threads.Add(thread);
}

threads.ForEach(t => t.Start());

foreach (var thread in threads)
{
thread.Join();
}

That(World.WorldSize, Is.EqualTo(originalWorldSize));
}
}
}
8 changes: 5 additions & 3 deletions src/Arch/Core/World.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ public partial class World
/// <summary>
/// Tracks how many <see cref="World"/>s exists.
/// </summary>
public static int WorldSize { get; private set; }
public static int WorldSize => Interlocked.CompareExchange(ref worldSizeUnsafe, 0, 0);

private static int worldSizeUnsafe;

/// <summary>
/// The shared static <see cref="JobScheduler"/> used for Multithreading.
Expand Down Expand Up @@ -114,7 +116,7 @@ public static World Create()
}

Worlds[recycledId] = world;
WorldSize++;
Interlocked.Increment(ref worldSizeUnsafe);
return world;
}
#endif
Expand All @@ -131,7 +133,7 @@ public static void Destroy(World world)
{
Worlds[world.Id] = null!;
RecycledWorldIds.Enqueue(world.Id);
WorldSize--;
Interlocked.Decrement(ref worldSizeUnsafe);
}
#endif

Expand Down

0 comments on commit 0c78c92

Please sign in to comment.