Threading, VecWorld & GIL Release

VecWorld Architecture (src/vec_world.cpp)

VecWorld(num_envs, num_threads, config) manages num_envs completely independent std::unique_ptr<World> instances, each with its own JPH::PhysicsSystem.

  • Worker count: When num_threads == 0, VecWorld picks min(num_envs, std::thread::hardware_concurrency()) (falling back to 4 if hardware_concurrency() returns 0).

  • Per-worker scratch memory & job system: If num_threads > 1, VecWorld spawns num_threads persistent std::thread workers (worker_loop), each owning:

    • A dedicated 16 MB JPH::TempAllocatorImplWithMallocFallback (worker_allocators_).

    • A JPH::JobSystemSingleThreaded (worker_job_systems_). Because environments are partitioned contiguously across workers ([start, end)), workers never share a PhysicsSystem or TempAllocator, avoiding cross-environment lock contention.

  • Synchronization: VecWorld::step() and VecWorld::raycast_batch() increment step_generation_ under mutex_, wake workers via cv_work_.notify_all(), wait on cv_done_ until active_workers_ == 0, and then gather contacts (on step).


Python GIL Release (src/python/module.cpp)

The following operations release the Python GIL (nb::gil_scoped_release) for their C++ execution:

  • World: step, raycast_batch, save_state, load_state

  • VecWorld: step, raycast_batch, reset_all, reset_envs, save_state, load_state

Thread-Safety Guarantees

  • Multiple independent World instances: Safe to step concurrently from Python threads (e.g., concurrent.futures.ThreadPoolExecutor), because ensure_jolt_initialized() is guarded by std::call_once and each World owns its own PhysicsSystem, TempAllocator, and JobSystem.

  • Single World or VecWorld instance: Not internally mutex-locked for concurrent Python calls to the same object. Do not call step(), add_body(), or mutate ctrl on the same World/VecWorld from multiple threads simultaneously.