Mutexes in Dart
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 isolates.
In this Dart version, we use a Lock
from the synchronized
package to implement mutual exclusion. The Container
class holds a map of counters, and we use the Lock
to synchronize access to this map.
The inc
method is now asynchronous, as it needs to acquire the lock before updating the counter.
Instead of goroutines, we use Dart’s Isolate
s for concurrent execution. The doIncrement
function is spawned in separate isolates to increment the counters.
We use a Completer
to wait for all isolates to finish their work before printing the final counter values.
Note that the zero value of a Lock
is usable as-is, so no initialization is required.
Running the program shows that the counters are updated as expected:
Next, we’ll look at implementing this same state management task using only isolates and ports for communication.