module
Docs::K_CONCURRENCY_CHANNELS_AND_ERGONOMICS
Overview
K. Concurrency, Channels & Engine Ergonomics
LibGodot bridges Crystal's fiber and thread models with Godot's multi-threaded engine architecture. This module details the actor concurrency primitives, thread safety invariants, and language ergonomics available to developers.
1. GodotChannel (Actor Concurrency)
Godot::Channel (registered in Godot's ClassDB as GodotChannel) is a
thread-safe, bounded or unbounded actor channel that can be passed between
Crystal and Godot/GDScript:
# Inside Crystal:
channel = Godot::Channel.new(capacity: 16)
# Spawn OS worker thread to crunch math:
Thread.new do
result = compute_heavy_simulation()
channel.send(result)
end
# In Crystal fiber or _process:
if item = channel.try_receive
apply_simulation(item)
end
In GDScript, GodotChannel emits signal received when data is sent,
allowing non-blocking reactive awaits:
# Inside GDScript:
func _ready():
var channel = GodotChannel.new(16)
# Asynchronously wait for data from Crystal worker
var data = await channel.received
print("Worker returned: ", data)
2. Concurrency Safety Rules
| Runtime Context | Allowed Operations | Forbidden Operations |
|---|---|---|
| Godot Main Thread | SceneTree mutations, node creation/destruction, try_receive, await_receive |
Blocking receive() (freezes window message pumping) |
| Crystal Fibers (spawn) | await(signal), await(timer), delay(sec), next_frame |
Top-level blocking sleep(sec) |
| Background OS Threads | Heavy computation, channel.send, call_deferred, blocking receive |
Direct SceneTree manipulation (add_child, queue_free) |
3. Resource & RefCounted DSL
In addition to the node macro, developers can declare custom Godot Resources
and RefCounted objects with @export properties:
resource ItemStats < Resource do
@[Export]
property damage : Int32 = 10
@[Export]
property rarity : String = "Legendary"
end
gdclass StateMachine < RefCounted do
@[Export]
property current_state : String = "idle"
end
4. Engine Async Helpers
Godot.next_frame: Cooperatively yields execution until the next render/process frame.Godot.physics_frame: Cooperatively yields execution until the next physics step.Godot.delay(seconds): Pauses execution for the given duration without halting the engine.Godot.spawn(&block): Spawns an exception-guarded cooperative fiber.
5. Collections Interoperability
Godot::Dictionarywraps Godot dictionaries and converts to/from CrystalHashviahash.to_godot_dictanddict.to_h.Godot::Array(T)wraps Godot arrays with fullEnumerablesupport and converts viaarray.to_godot_arrayandarr.to_a.