Atomic Counters in AngelScript

import std.threading;
import std.atomic;

void main()
{
    // We'll use an atomic integer type to represent our
    // (always-positive) counter.
    Atomic<uint64> ops;

    // A thread group will help us wait for all threads
    // to finish their work.
    ThreadGroup threads;

    // We'll start 50 threads that each increment the
    // counter exactly 1000 times.
    for (int i = 0; i < 50; i++)
    {
        threads.create(function()
        {
            for (int c = 0; c < 1000; c++)
            {
                // To atomically increment the counter we use increment().
                ops.increment();
            }
        });
    }

    // Wait until all the threads are done.
    threads.joinAll();

    // Here no threads are writing to 'ops', but using
    // get() it's safe to atomically read a value even while
    // other threads are (atomically) updating it.
    print("ops: " + ops.get());
}

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:

ops: 50000

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.