Channels in AngelScript

Channels in AngelScript

In this example, we will demonstrate the use of channels to communicate between concurrent functions using AngelScript.

void main() {
    auto messages = Channel<string>(1);
    
    thread( 
        function() {
            messages.put("ping");
        }
    );

    string msg = messages.get();
    print(msg + "\n");
}

Channels in AngelScript are a way for different threads to communicate. We create a new channel with Channel<string>(1), which specifies that the channel can hold one string value.

We start a new thread with thread, and within that thread, we put the string “ping” into the channel using messages.put("ping");.

In the main function, we receive the value from the channel with messages.get() and then print it.

To run the program, save the code in a file (e.g., channels.as) and run it using an AngelScript environment.

asc channels.as

When the program runs, the “ping” message is successfully sent from the thread to the main function via the channel, and it gets printed.

By default, put and get operations block until both the sender and receiver are ready. This property allows us to wait at the end of our program for the “ping” message without needing to use any additional synchronization.

Now that we have learned how to use channels in AngelScript, we can explore more about concurrent programming in AngelScript.