Goroutines in GDScript

Based on the specified language (GDScript) and the provided Go code example, here is the translated output in Markdown format suitable for Hugo.


A goroutine is a lightweight thread of execution.

extends Node

func _ready():
    f("direct")
    start_goroutine("goroutine")
    start_goroutine(lambda(): print("going"))

    yield(get_tree().create_timer(1), "timeout")
    print("done")

func f(from):
    for i in range(3):
        print("%s : %d" % [from, i])

func start_goroutine(func_ref):
    var _thread = Thread.new()
    _thread.start(self, func_ref, [])

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

    f("direct")

To invoke this function in a thread, use the start_goroutine function. This new thread will execute concurrently with the calling one.

    start_goroutine("f", ["goroutine"])

You can also start a thread for an anonymous function call.

    start_goroutine(lambda(): print("going"))

Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, use await or signal connections).

To see the output of this program, play the scene in Godot. You will first see the output of the blocking call, followed by the output of the two threads, which may be interleaved because threads are being run concurrently by the Godot engine.