Channel Synchronization in Scilab

Our example demonstrates how to synchronize execution across different threads. We’ll use a channel-like mechanism to wait for a worker thread to finish. When waiting for multiple threads to finish, you might prefer to use a join() method.

function worker(done)
    mprintf("working...")
    sleep(1000)
    mprintf("done\n")
    done.value = %t
endfunction

function main()
    // Create a mlist to simulate a channel
    done = mlist(['channel', 'value'], %f)
    
    // Start a worker thread, giving it the channel to notify on
    worker_thread = createThread(worker, done)
    
    // Block until we receive a notification from the worker on the channel
    while ~done.value
        sleep(100)
    end
endfunction

main()

This is the function we’ll run in a separate thread. The done mlist will be used to notify the main thread that this function’s work is done.

In the main function, we start a worker thread, passing it the done mlist. We then enter a loop that blocks until we receive a notification from the worker.

To run the program:

--> exec('channel_synchronization.sce')
working...done

If you removed the while loop from this program, the program would exit before the worker even started.

Note that Scilab doesn’t have built-in support for channels or goroutines like some other languages. This example simulates similar behavior using Scilab’s threading capabilities and a simple mlist structure to pass information between threads. The createThread function is used to start a new thread, and we use a while loop to wait for the thread to finish, checking the value of our done mlist.