Rules for running physics on separate thread

Godot Version

4.6

Question

Dear Godot Veterans,

So I am playing around with Physics 3D > “Run on Separate Thread” → on.

And I see right away that get_world_3d().direct_space_state returned null. Fortunately, the document is helpful in that it states that with multi-thread, it will only work in _physics_process(). So I move everything there and things seem to be fine.

Nowaday, all of our computers are pretty much multi-core, so going for this might seem like a good idea, but there are a few things that we should be mindful of. From searching around:

  1. The second paragraph above.
  2. You cannot do add_child(), queue_free() or modify nodes on _physics_process(). If you would like to do that, use call_deferred to handle this.
  3. Body state should (not forbidden) be done in _physics_process(): This includes global_transform, linear_velocity, angular_velocity, apply_impulse(), add_force(), etc. Trying to read these values outside _physics_process() could have values one frame behind or inconsistent or race-condition prone.
  4. Signals such as body_entered, body_exited, area_entered and area_exited are delivered on the main thread, not physics thread, even though the physics objects are processed in the physics thread. This means you can do things like queue_free() in those functions just fine.
  5. From Thread-safe APIs — Godot Engine (4.6) documentation in English, reading and writing elements from multiple threads is OK, but anything that changes the container size (resizing, adding, or removing elements) requires locking a mutex. I believe failure to do so could make your game go into undefined behavior, such as:
  • Random crashes
  • Memory corruption (worst case, hardest to debug)
  • Missing or duplicated elements
  • Heisenbugs (works 99% of the time, fails randomly)

But still, if the threads are designed to never need to modify size of the same arrays or dictionaries, then this should not be a concern. But if so, then use mutex.

These are some of the “rules” I found so far. Are there other things I should be aware of? So far, have you ran into any noteworthy issue?

Note: if anything above is incorrect, please feel free to point out.

1 Like