Waitgroups in GDScript

Our program will demonstrate the use of a concurrent execution pattern similar to WaitGroups. In GDScript, we’ll use threads and a semaphore to achieve a similar effect. Here’s the full source code:

extends Node

var semaphore: Semaphore
var thread_count = 5

func _ready():
    semaphore = Semaphore.new()
    
    for i in range(1, thread_count + 1):
        var thread = Thread.new()
        thread.start(self, "worker", i)
    
    # Wait for all threads to complete
    for i in range(thread_count):
        semaphore.wait()
    
    print("All workers completed")

func worker(id):
    print("Worker %d starting" % id)
    
    # Simulate an expensive task
    OS.delay_msec(1000)
    
    print("Worker %d done" % id)
    
    # Signal that this worker is done
    semaphore.post()

This script demonstrates a pattern similar to WaitGroups using GDScript’s threading capabilities. Here’s how it works:

  1. We create a Semaphore object to keep track of the number of active workers.

  2. We launch several threads (in this case, 5) and increment the semaphore for each.

  3. Each worker thread prints a start message, simulates work with a delay, and then prints a completion message.

  4. After the work is done, each worker signals completion by calling semaphore.post().

  5. In the main thread, we wait for all workers to complete by calling semaphore.wait() for each worker.

  6. Once all workers have completed, we print a final message.

To run this script, you would typically attach it to a Node in your Godot scene. The output might look something like this:

Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 2 done
Worker 3 done
Worker 4 done
Worker 5 done
All workers completed

Note that the order of workers starting and finishing may vary between runs due to the nature of concurrent execution.

This approach in GDScript provides a way to manage multiple threads and wait for their completion, similar to the WaitGroup concept. However, it’s important to note that GDScript’s threading model is more limited compared to some other languages, and care should be taken when using threads in game development to avoid issues with the main game loop and rendering.