Work in progress

The content of this page was not yet updated for Godot 4.2 and may be outdated. If you know how to improve this page or you can confirm that it's up to date, feel free to open a pull request.

Потокобезопасные API

Потоки

Потоки используются для балансировки вычислительной мощности между процессорами и ядрами. Godot поддерживает многопоточность, но не во всем движке.

Ниже приведен список способов, которыми многопоточность может быть использована в различных областях Godot.

Глобальная область

Global Scope singletons are all thread-safe. Accessing servers from threads is supported (for RenderingServer 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:
node.add_child(child_node)
# Safe:
node.call_deferred("add_child", child_node)

Хотя, создание чанков сцены (нодов в древе) вне активного древа нормально. Таким образом, части сцены могут быть собраны или инстанцированы из потока, а затем добавлены в главный поток:

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

Still, this is only really useful if you have one thread loading data. Attempting to load or create scene chunks from multiple threads may work, but you risk resources (which are only loaded once in Godot) tweaked by the multiple threads, resulting in unexpected behaviors or crashes.

Only use more than one thread to generate scene data if you really know what you are doing and you are sure that a single resource is not being used or set in multiple ones. Otherwise, you are safer just using the servers API (which is fully thread-safe) directly and not touching scene or resources.

Рендеринг

Instancing nodes that render anything in 2D or 3D (such as Sprite) is not thread-safe by default. To make rendering thread-safe, set the Rendering > Driver > Thread Model project setting to Multi-Threaded.

Note that the Multi-Threaded thread model has several known bugs, so it may not be usable in all scenarios.

You should avoid calling functions involving direct interaction with the GPU on other threads, such as creating new textures or modifying and retrieving image data, these operations can lead to performance stalls because they require synchronization with the RenderingServer, as data needs to be transmitted to or updated on the GPU.

GDScript массивы, словари

In GDScript, 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.

Ресурсы

Изменение уникального ресурса из нескольких потоков не поддерживается. Однако работа со ссылками в нескольких потоках поддерживается, поэтому загрузка ресурсов в поток также поддерживается - сцены, текстуры, сетки и т.д. могут быть загружены и обработаны в потоке, а затем добавлены в активную сцену в основном потоке. Ограничением здесь является то, что, как описано выше, нужно быть осторожным, чтобы не загрузить один и тот же ресурс из нескольких потоков одновременно, поэтому проще всего использовать один поток для загрузки и изменения ресурсов, а затем основной поток для их добавления.