Repository navigation
fix: Create and destroy worlds under a process-wide lock - #127
Merged
spydon merged 4 commits intoOct 19, 2026
Merged
Conversation
Box2D keeps every world in one process-wide table, and b2CreateWorld and b2DestroyWorld claim and free its slots without synchronization; Box2D leaves the guard to the caller (erincatto/box2d#904, and the manual's "Multithreading Multiple Worlds"). Dart isolates are threads over one copy of the native library, so isolates creating and destroying worlds at the same time could put two worlds in one slot, which crashed or computed garbage. The native backend now creates and destroys worlds through a small C shim, native/ffi/f2d_world_lock.c, that holds a process-wide mutex around both calls. The WebAssembly backend is single-threaded and unchanged.
Use Box2D's own atomics for a spinlock instead of pthread and SRWLOCK, which removes the platform branches and the pthread link. Also trim duplicated documentation and simplify the isolates test.
spydon
force-pushed
the
fix/world-create-destroy-race
branch
from
October 19, 2026 07:46
3397c56 to
3d75950
Compare
Spin on a plain read before the compare-exchange, keep forge2d's own C sources apart from the vendored Box2D list, shorten the header comment, and avoid abbreviated parameter names.
World now throws a StateError when the world table is full instead of wrapping an invalid id. b2CreateWorld and b2DestroyWorld are excluded from the generated bindings so only the locked wrappers can be called.
5 of 7 tasks
spydon
added a commit
that referenced
this pull request
Oct 19, 2026
# Description Box2D's length unit is process-wide, and `initializeForge2D` refuses to change it once a `World` exists, since every world was built for the old unit. The flag that tracked whether a world exists was a Dart static, though, and each isolate has its own copy of Dart statics. So isolate B could still change the length unit under isolate A's live worlds, which is exactly the silent corruption the `StateError` is meant to prevent. #127 documents that several isolates can each run worlds, which makes this easier to hit. This PR: - moves the flag behind the backend. `RawBox2D.setLengthUnitsPerMeter` becomes `trySetLengthUnitsPerMeter`, which refuses the change once a world has been created, and a new `resetLengthUnitLock` backs `debugResetLengthUnitLock`; - on the native backend, keeps the flag in `native/ffi/f2d_world_lock.c`. Creating a world sets it, and setting the length unit checks it, both under the world lock from #127, so the check and the change cannot race with another isolate creating a world; - on the WebAssembly backend, keeps the flag in the backend instance. It runs on one thread and each module instance has its own length unit, so no lock is needed; - removes `markWorldCreated` from `World`, since the backends now track this themselves; - adds a test where one isolate holds a world and another tries to change the length unit, and makes `length_unit_test.dart` reset the flag first, since earlier suites in the same process have now created worlds. No public API changes. Code that changes the length unit from another isolate after a world exists now gets the `StateError` instead of silently corrupting the simulation. Testing (macOS arm64): the new test fails without the fix. With it, the full suite (117 tests) passes on the VM, the length unit, world and tolerance tests pass on the WebAssembly backend in Chrome, and `dart analyze --fatal-infos` and `dart format` are clean. ## Checklist - [x] The title of my PR starts with a [Conventional Commit] prefix (`fix:`, `feat:`, `docs:` etc). - [x] I have read the [Contributor Guide] and followed the process outlined for submitting PRs. - [x] I have updated/added tests for ALL new/updated/fixed functionality. - [x] I have updated/added relevant documentation in `docs` and added dartdoc comments with `///`. - [ ] I have updated/added relevant examples in `examples`. ## Breaking Change - [ ] Yes, this is a breaking change. - [x] No, this is *not* a breaking change. ## Related Issues Follow-up to #127. [Contributor Guide]: https://github.com/flame-engine/flame/blob/main/CONTRIBUTING.md [Conventional Commit]: https://conventionalcommits.org
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Box2D keeps every world in one process-wide table, and
b2CreateWorldandb2DestroyWorldclaim and free its slots without synchronization. Box2D leaves the guard to the caller (manual, Multithreading Multiple Worlds: "You should use a mutex to guard this"; erincatto/box2d#904). Dart isolates are threads over one copy of the native library, so isolates creating and destroying worlds at the same time could put two worlds in one slot, which crashes the VM or computes garbage. This is easy to hit downstream, sincedart testruns test files as concurrent isolates in one process. See the issue for details and a reproduction.Existing behaviour: the FFI backend called
b2CreateWorldandb2DestroyWorlddirectly.This PR:
native/ffi/f2d_world_lock.c, which wraps the two calls in a process-wide spinlock built on Box2D's own atomics (atomic.h), so there are no platform-specific branches and no extra libraries to link. The build hook compiles it into the same library as Box2D, so the vendored Box2D sources stay untouched;lib/src/ffi/f2d_world_lock.dart(hand-written, next to the generatedbox2d.g.dart) and calls them fromraw_box2d_ffi.dart;b2CreateWorldandb2DestroyWorldfrom the generated bindings intool/ffigen/ffigen.yaml, so only the locked wrappers can be called. The FFI smoke test uses the wrappers too;World()throw aStateErrorwhen Box2D's table of 128 worlds is full, instead of wrapping an invalid id. The table is shared by every isolate in the process, so it is easier to fill than before;test/api/isolates_test.dart: 8 isolates each create, step and destroy 500 small worlds and must get exactly the result the main isolate got, and a test intest/api/world_test.dartfor the full world table;World's dartdoc that several isolates can each run worlds of their own at the same time.The WebAssembly backend is unchanged: it runs on one thread, and each module instance has its own memory and world table.
A Dart-side lock was not an option: there is no lock in stable Dart that spans isolates.
Only creating and destroying a world are locked. Everything else a world does touches that world alone, which still has to be used from the isolate that created it. No public API changes, apart from the new
StateErrorwhen no world can be created.Testing (macOS arm64): with the lock calls disabled, the new test crashes the VM. With them, the full suite (116 tests) passes repeatedly, and
dart analyze --fatal-infosanddart formatare clean. Linux and Windows are covered by CI.Checklist
fix:,feat:,docs:etc).docsand added dartdoc comments with///.examples.(No example: the change has no API of its own. This repo has no
docsfolder.)Breaking Change
Related Issues
Fixes #126