Channel Synchronization in GDScript

This example demonstrates how to use signals (GDScript’s equivalent to channels) to synchronize execution across different threads. We’ll use a blocking wait to wait for a thread to finish. When waiting for multiple threads to finish, you might prefer to use GDScript’s yield() function or a custom semaphore implementation.

extends Node

# This is the function we'll run in a thread. The
# 'done' signal will be used to notify the main thread
# that this function's work is done.
func worker():
    print("working...")
    yield(get_tree().create_timer(1.0), "timeout")
    print("done")
    
    # Emit a signal to notify that we're done.
    emit_signal("done")

# Define the 'done' signal
signal done

func _ready():
    # Connect the 'done' signal to a method
    connect("done", self, "_on_worker_done")
    
    # Start a worker thread
    call_deferred("worker")
    
    # The main thread continues execution...
    print("Waiting for worker...")

# This function will be called when the 'done' signal is emitted
func _on_worker_done():
    print("Worker has finished")

To run the program, save it as a script attached to a Node in your Godot project and run the scene.

working...
Waiting for worker...
done
Worker has finished

If you removed the connect("done", self, "_on_worker_done") line from this program, the _on_worker_done function would never be called, and you wouldn’t know when the worker has finished.

Note that GDScript doesn’t have built-in support for true multithreading. The call_deferred function is used to schedule the worker function to run on the next idle frame, simulating asynchronous behavior. For true parallel execution, you would need to use GDScript’s Thread class, which is more complex and not shown in this basic example.