Select in AngelScript

Our example demonstrates how to wait on multiple operations using a select-like mechanism. Combining threads and message passing with this feature is a powerful aspect of AngelScript.

import std.time;
import std.string;

void main()
{
    // For our example we'll select across two message queues.
    array<string> q1, q2;

    // Each queue will receive a value after some amount
    // of time, to simulate e.g. blocking operations
    // executing in concurrent threads.
    thread_create(function() {
        sleep(1000); // Sleep for 1 second
        q1.insertLast("one");
    });
    thread_create(function() {
        sleep(2000); // Sleep for 2 seconds
        q2.insertLast("two");
    });

    // We'll use a loop to await both of these values
    // simultaneously, printing each one as it arrives.
    for (int i = 0; i < 2; i++)
    {
        while (true)
        {
            if (!q1.isEmpty())
            {
                print("received " + q1[0] + "\n");
                q1.removeAt(0);
                break;
            }
            else if (!q2.isEmpty())
            {
                print("received " + q2[0] + "\n");
                q2.removeAt(0);
                break;
            }
            yield(); // Allow other threads to run
        }
    }
}

We receive the values “one” and then “two” as expected.

$ angelscript select.as
received one
received two

Note that the total execution time is only ~2 seconds since both the 1 and 2 second sleeps execute concurrently.

In this AngelScript version, we’ve simulated the behavior of Go’s select statement using a loop and checking message queues. The thread_create function is used to spawn new threads, similar to goroutines in Go. The yield() function is called to allow other threads to run, simulating concurrent execution.

Keep in mind that AngelScript’s threading model may differ from Go’s, and the exact behavior might vary depending on the specific AngelScript implementation and host application.