Thread-safe APIs


Threads are used to balance processing power across CPUs and cores. Godot supports multithreading, but not in the whole engine.



Global Scope singletons are all thread-safe. Accessing servers from threads is supported (for VisualServer and Physics servers, ensure threaded or thread-safe operation is enabled in the project settings!).

这使它们成为在服务器中创建数十万个实例并从线程控制它们的代码的理想选择。 当然,还需要更多的代码, 因为这是直接使用的而不是嵌入场景树中使用 。


Interacting with the active scene tree is NOT thread-safe. Make sure to use mutexes when sending data between threads. If you want to call functions from a thread, the call_deferred function may be used:

# Unsafe:
# Safe:
node.call_deferred("add_child", child_node)

但是,可以在激活的场景树外创建场景块(以树形式排列的节点)。 这样,可以在线程中构建或实例化部分场景,然后将其添加到主线程中:

var enemy_scene = load("res://enemy_scene.scn").instance()
var enemy = enemy_scene.instance()
enemy.add_child(weapon) # Set a weapon.
world.call_deferred("add_child", enemy)






Modifying a unique resource from multiple threads is not supported. However handling references on multiple threads is supported, hence loading resources on a thread is as well - scenes, textures, meshes, etc - can be loaded and manipulated on a thread and then added to the active scene on the main thread. The limitation here is as described above, one must be careful not to load the same resource from multiple threads at once, therefore it is easiest to use one thread for loading and modifying resources, and then the main thread for adding them.