Mutexes in GDScript
In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a mutex to safely access data across multiple threads.
In this GDScript version:
We define a
Container
class that holds a map of counters. We use aMutex
to synchronize access to this map.The
inc
method locks the mutex before accessingcounters
, and unlocks it afterwards. In GDScript, we don’t have adefer
statement, so we explicitly unlock the mutex at the end of the function.In the
_ready
function (which is similar tomain
in GDScript), we create aContainer
instance and set up our counters.We define a
do_increment
function that increments a named counter in a loop.We create and start three threads, two incrementing counter “a” and one incrementing counter “b”.
We wait for all threads to finish using
wait_to_finish()
.Finally, we print the counters.
Running this program should show that the counters are updated as expected:
Note that in GDScript, we use threads instead of goroutines, and a Mutex
instead of sync.Mutex
. The concept is similar, but the implementation details differ slightly due to the differences between the languages.
Next, we’ll look at implementing this same state management task using only threads and signals (which are similar to channels in GDScript).