module
Lapis::Docs::D_CONCURRENCY_AND_FIBERS::C_MAIN_THREAD_DISPATCH
Overview
Main Thread Queue & Thread-Safe Dispatch
Comprehensive guide to dispatching closures and methods from background OS worker threads back onto the Godot Engine main thread.
Executive Summary & Key Topics
| Topic | Method / Anchor | Description |
|---|---|---|
| Thread-Safe Notification Mechanisms | .topic_00_dispatch_methods |
Godot.on_main_thread closures vs Godot engine call_deferred. |
| Scheduling Work with Godot.on_main_thread | .topic_01_on_main_thread |
Enqueueing Crystal closures from background workers to mutate nodes safely. |
Related Guides & Source References
- Thread Safety Engine:
src/libgodot/thread_safety.cr - Macros:
src/libgodot/macros.cr
Defined in:
libgodot/docs/d_concurrency_and_fibers/c_main_thread_dispatch.crClass Method Summary
-
.topic_00_dispatch_methods : Nil
Thread-Safe Notification Mechanisms: Godot.on_main_thread closures vs Godot engine call_deferred.
-
.topic_01_on_main_thread : Nil
Scheduling Work with Godoton_main_thread: Enqueueing Crystal closures from background workers to mutate nodes safely.
Class Method Detail
Thread-Safe Notification Mechanisms: Godot.on_main_thread closures vs Godot engine call_deferred.
Key Topics & Information
- Godot.on_main_thread { ... }: Crystal closure queue flushed every frame in _process
- node.call_deferred(method, *args): Godot engine MessageQueue dispatch
- ThreadSafety.assert_main_thread!: Defensive guard against illegal background mutation
Scheduling Work with Godoton_main_thread: Enqueueing Crystal closures from background workers to mutate nodes safely.
When a background worker thread needs to create nodes or update the SceneTree:
Thread.new do
heavy_procedural_texture = generate_terrain_noise
# Safely hand off to main thread:
Godot.on_main_thread do
sprite = Godot.create(Godot::Sprite2D)
sprite.texture = heavy_procedural_texture
add_child(sprite) # SAFE: Dispatched on the engine main thread!
end
end
How It Works:
The queue is thread-safe and guarded by a ::Thread::Mutex. On every frame during _process and _physics_process, Godot::ThreadSafety.flush_main_thread_queue! drains the queue and executes the closures on the main thread.