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.
Running the program shows that the counters updated as expected.
In this Lua implementation, we use the lanes library to provide multi-threading capabilities and mutex synchronization. The Container class is implemented as a Lua table with methods. The mutex is created using lanes.mutex().
The doIncrement function is defined locally and then passed to lanes.gen() to create new threads. We use a table to keep track of the threads and join them at the end to wait for their completion.
Note that Lua doesn’t have built-in support for concurrency, so we rely on the lanes library to provide this functionality. This approach may differ from the original Go implementation in some details, but it achieves the same goal of safely managing shared state across multiple threads.
Next we’ll look at implementing this same state management task using only coroutines and channels.