diff --git a/docs/soa-world.md b/docs/soa-world.md index e1a7300..3f3c13e 100644 --- a/docs/soa-world.md +++ b/docs/soa-world.md @@ -62,6 +62,10 @@ Unity consumption is unrun; cross-platform bit-identity is unclaimed. `bin\$(Configuration)\` on every platform: `CMakeLists.txt` writes `bin/$/` and the csproj passes `-DCMAKE_BUILD_TYPE=$(Configuration)`, so single- and multi-config generators land in the same place. - Windows run: MinGW gcc with `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; `Ymir.Box3D.Soa.Tests` passes. Linux run (Yggdrasil, default generator, gcc): the same tests pass and emit `bin/Debug/libymir_box3d.so`. macOS is unrun. +- Threading: creating and destroying worlds is safe from any number of threads at once (a process-wide lock in the native + layer serializes `b3CreateWorld`/`b3DestroyWorld`, which otherwise scan and rewrite Box3D's global world pool unsynchronized; + the retained session and pair-step paths take the same lock). Stepping distinct worlds concurrently is safe. A single world + is still not thread-safe. `Box3DSoaConcurrentCreateTests` creates, steps and disposes worlds from eight threads. - `Box3DSoaWorld` is not thread-safe: `Dispose` must not race `Step` or a lane read. A `Box3DSoaView` refuses to hand out a lane (ObjectDisposedException) once its world is disposed, and a `default` view refuses with InvalidOperationException. The check guards obtaining a span, not a span already held: a span taken from a diff --git a/native/Ymir.Box3D/ymir_box3d.c b/native/Ymir.Box3D/ymir_box3d.c index e42ff7c..860bbbd 100644 --- a/native/Ymir.Box3D/ymir_box3d.c +++ b/native/Ymir.Box3D/ymir_box3d.c @@ -10,6 +10,39 @@ #include #include +#include "ymir_world_lock.h" + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +static SRWLOCK ymir_world_pool_lock = SRWLOCK_INIT; +#define YMIR_WORLD_POOL_LOCK() AcquireSRWLockExclusive(&ymir_world_pool_lock) +#define YMIR_WORLD_POOL_UNLOCK() ReleaseSRWLockExclusive(&ymir_world_pool_lock) +#else +#include +static pthread_mutex_t ymir_world_pool_lock = PTHREAD_MUTEX_INITIALIZER; +#define YMIR_WORLD_POOL_LOCK() pthread_mutex_lock(&ymir_world_pool_lock) +#define YMIR_WORLD_POOL_UNLOCK() pthread_mutex_unlock(&ymir_world_pool_lock) +#endif + +b3WorldId ymir_create_world_locked(const b3WorldDef* def) +{ + YMIR_WORLD_POOL_LOCK(); + b3WorldId world_id = b3CreateWorld(def); + YMIR_WORLD_POOL_UNLOCK(); + return world_id; +} + +void ymir_destroy_world_locked(b3WorldId world_id) +{ + YMIR_WORLD_POOL_LOCK(); + b3DestroyWorld(world_id); + YMIR_WORLD_POOL_UNLOCK(); +} + + #if defined(_WIN32) #define YMIR_EXPORT __declspec(dllexport) #define YMIR_CALL __cdecl @@ -1164,7 +1197,7 @@ YMIR_EXPORT void YMIR_CALL ymir_box3d_step_pair( world_def.gravity = b3Vec3_zero; world_def.enableSleep = false; world_def.restitutionThreshold = restitution_threshold; - b3WorldId world_id = b3CreateWorld(&world_def); + b3WorldId world_id = ymir_create_world_locked(&world_def); b3BodyId body_a = ymir_create_body(world_id, body_a_input); b3BodyId body_b = ymir_create_body(world_id, body_b_input); @@ -1177,7 +1210,7 @@ YMIR_EXPORT void YMIR_CALL ymir_box3d_step_pair( result->end_contact_count = events.endCount; result->hit_contact_count = events.hitCount; - b3DestroyWorld(world_id); + ymir_destroy_world_locked(world_id); } YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float torque, float time_step, int32_t sub_step_count) @@ -1185,7 +1218,7 @@ YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float b3WorldDef world_def = b3DefaultWorldDef(); world_def.gravity = b3Vec3_zero; world_def.enableSleep = false; - b3WorldId world_id = b3CreateWorld(&world_def); + b3WorldId world_id = ymir_create_world_locked(&world_def); ymir_box3d_body_input input = { .radius = 1.0f, @@ -1199,7 +1232,7 @@ YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float b3World_Step(world_id, time_step, sub_step_count); float after_unforced_step = b3Body_GetAngularVelocity(body_id).y; - b3DestroyWorld(world_id); + ymir_destroy_world_locked(world_id); return (ymir_box3d_torque_result){after_applied_step, after_unforced_step}; } @@ -1253,7 +1286,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_create(ymir_box3d_session** out world_def.gravity = b3Vec3_zero; world_def.enableSleep = false; world_def.workerCount = 1; - session->world_id = b3CreateWorld(&world_def); + session->world_id = ymir_create_world_locked(&world_def); if (B3_IS_NULL(session->world_id)) { free(session); @@ -1273,7 +1306,7 @@ YMIR_EXPORT void YMIR_CALL ymir_box3d_session_destroy(ymir_box3d_session* sessio if (B3_IS_NON_NULL(session->world_id) && b3World_IsValid(session->world_id)) { - b3DestroyWorld(session->world_id); + ymir_destroy_world_locked(session->world_id); } free(session->bodies); free(session->contact_events); diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index af2fe78..9420a81 100644 --- a/native/Ymir.Box3D/ymir_box3d_soa.c +++ b/native/Ymir.Box3D/ymir_box3d_soa.c @@ -14,6 +14,8 @@ #include #include +#include "ymir_world_lock.h" + #include #include #include @@ -334,7 +336,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( def.gravity = (b3Vec3){gravity_x, gravity_y, gravity_z}; def.enableSleep = false; def.workerCount = 1; // one worker: the step order is fixed, which determinism rests on - world->world_id = b3CreateWorld(&def); + world->world_id = ymir_create_world_locked(&def); if (B3_IS_NULL(world->world_id)) { ymir_soa_free(world); @@ -353,7 +355,7 @@ YMIR_EXPORT void YMIR_CALL ymir_box3d_soa_destroy(ymir_box3d_soa_world* world) } if (B3_IS_NON_NULL(world->world_id) && b3World_IsValid(world->world_id)) { - b3DestroyWorld(world->world_id); + ymir_destroy_world_locked(world->world_id); } ymir_soa_free(world); } diff --git a/native/Ymir.Box3D/ymir_world_lock.h b/native/Ymir.Box3D/ymir_world_lock.h new file mode 100644 index 0000000..ea6fb82 --- /dev/null +++ b/native/Ymir.Box3D/ymir_world_lock.h @@ -0,0 +1,12 @@ +// Process-wide lock around Box3D world creation and destruction. b3CreateWorld and b3DestroyWorld scan +// and rewrite the global world pool (b3_worlds) with no synchronization, so two threads creating worlds +// at once can claim the same slot and corrupt it. Stepping and every other call touch only the caller's +// own world and stay unlocked. A single world is still not thread-safe. One lock, defined in +// ymir_box3d.c, serves every translation unit. +#pragma once + +#include +#include + +b3WorldId ymir_create_world_locked(const b3WorldDef* def); +void ymir_destroy_world_locked(b3WorldId world_id); diff --git a/tests/Ymir.Box3D.Soa.Tests/AssemblyInfo.cs b/tests/Ymir.Box3D.Soa.Tests/AssemblyInfo.cs deleted file mode 100644 index 8e22081..0000000 --- a/tests/Ymir.Box3D.Soa.Tests/AssemblyInfo.cs +++ /dev/null @@ -1,4 +0,0 @@ -// Box3D world creation is not safe to run concurrently in one process: two threads calling -// b3CreateWorld abort the host (found when two test classes created worlds at once). Tests that create -// worlds run one at a time. -[assembly: CollectionBehavior(DisableTestParallelization = true)] diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaConcurrentCreateTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaConcurrentCreateTests.cs new file mode 100644 index 0000000..386a1bd --- /dev/null +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaConcurrentCreateTests.cs @@ -0,0 +1,46 @@ +using Ymir.Box3D; + +namespace Ymir.Box3D.Soa.Tests; + +public sealed class Box3DSoaConcurrentCreateTests +{ + /// + /// Box3D's world pool is a process-global array scanned without a lock; without the native + /// create/destroy lock, concurrent creation claims one slot twice and aborts the host. + /// Each thread creates, steps and disposes many worlds while the others do the same. + /// + [Fact] + public void Worlds_created_stepped_and_disposed_from_many_threads_do_not_crash() + { + const int threads = 8; + const int rounds = 200; + using var start = new ManualResetEventSlim(false); + var failures = new List(); + + var workers = Enumerable.Range(0, threads).Select(t => new Thread(() => + { + try + { + start.Wait(); + for (var r = 0; r < rounds; r++) + { + using var world = new Box3DSoaWorld(capacity: 8); + world.AddStaticBox(1, (0f, -0.5f, 0f), (10f, 0.5f, 10f)); + world.AddSphere(2, (0f, 2f, 0f), radius: 0.5f, density: 1f, velocity: (0f, 0f, 0f)); + for (var s = 0; s < 3; s++) world.Step(1f / 60f); + if (world.View.Count != 2) throw new InvalidOperationException("lane count"); + } + } + catch (Exception e) + { + lock (failures) failures.Add(e); + } + })).ToArray(); + + foreach (var w in workers) w.Start(); + start.Set(); + foreach (var w in workers) w.Join(); + + Assert.Empty(failures); + } +}