Select in Scilab

Our example demonstrates how to wait on multiple channel-like operations. Combining parallel execution and communication channels is a powerful feature in scientific computing.

function select_example()
    // For our example we'll select across two channels.
    c1 = [];
    c2 = [];

    // Each channel will receive a value after some amount
    // of time, to simulate e.g. blocking operations
    // executing in parallel.
    function delayed_send(channel, value, delay)
        sleep(delay * 1000);
        channel($+1) = value;
    endfunction

    parallel_run(delayed_send, list(c1, "one", 1));
    parallel_run(delayed_send, list(c2, "two", 2));

    // We'll use a loop to await both of these values
    // simultaneously, printing each one as it arrives.
    for i = 1:2
        while isempty(c1) & isempty(c2)
            sleep(100);
        end
        
        if ~isempty(c1) then
            msg1 = c1(1);
            c1(1) = [];
            disp("received " + msg1);
        elseif ~isempty(c2) then
            msg2 = c2(1);
            c2(1) = [];
            disp("received " + msg2);
        end
    end
endfunction

// Run the example
tic();
select_example();
execution_time = toc();
disp("Execution time: " + string(execution_time) + " seconds");

In this Scilab implementation, we use arrays (c1 and c2) to simulate channels. The parallel_run function is used to start parallel executions, similar to goroutines. We use a polling mechanism to check for new values in our “channels”.

To run the program, save it as select_example.sce and execute it in Scilab:

--> exec('select_example.sce', -1)
received one
received two
Execution time: 2.0101 seconds

We receive the values “one” and then “two” as expected. Note that the total execution time is only about 2 seconds since both the 1 and 2 second delays execute concurrently.

This example demonstrates how to implement concurrent operations and synchronization in Scilab, even though it doesn’t have built-in support for channels or select statements like some other languages.