Atomic Counters in AngelScript
This example demonstrates the use of atomic counters in AngelScript, which are accessed by multiple threads. The primary mechanism for managing state in AngelScript is typically through message passing or shared memory with proper synchronization. Here, we’re looking at using the std.atomic
module for atomic counters.
We use an Atomic<uint64>
type to represent our always-positive counter. A ThreadGroup
is used to help us wait for all threads to finish their work.
We start 50 threads, each incrementing the counter exactly 1000 times. To atomically increment the counter, we use the increment()
method.
After waiting for all threads to complete using threads.joinAll()
, we safely read the final value of the counter using the get()
method.
When you run this program, you should see:
We expect to get exactly 50,000 operations. If we had used a non-atomic integer and incremented it with regular addition, we’d likely get a different number, changing between runs, because the threads would interfere with each other.
Next, we could look at mutexes, another tool for managing state in concurrent programming.