Stateful Goroutines in GDScript
Our example demonstrates how to manage state using GDScript’s built-in threading and signal mechanisms. This approach aligns with GDScript’s ideas of sharing data through communication.
In this example, we use GDScript’s threading and signals to manage shared state. The state is owned by a single thread, which responds to read and write requests sent via signals.
We start by defining ReadOp
and WriteOp
classes to encapsulate our read and write operations.
The _manage_state
function runs in its own thread and owns the state
dictionary. It continuously waits for read or write requests and processes them.
We then start 100 threads to perform read operations and 10 threads to perform write operations. Each operation is performed by emitting a signal with the appropriate operation object.
After letting the operations run for a second, we print out the total number of read and write operations performed.
This approach ensures that the state is never corrupted by concurrent access, as all access is managed by a single thread. It demonstrates how to use GDScript’s built-in concurrency features to safely manage shared state.
Running this program will show the number of read and write operations completed in one second, which should be in the tens of thousands.
This method might be more complex than using mutexes, but it can be useful in scenarios involving multiple channels or when managing multiple mutexes would be error-prone. Choose the approach that feels most natural and helps you ensure the correctness of your program.