Mutexes in Scilab

In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a mutex to safely access data across multiple threads.

function [c] = Container()
    c.mu = semaphore('init', 1);
    c.counters = struct('a', 0, 'b', 0);
endfunction

function inc(c, name)
    semaphore('lock', c.mu);
    c.counters(name) = c.counters(name) + 1;
    semaphore('unlock', c.mu);
endfunction

function main()
    c = Container();
    
    function doIncrement(name, n)
        for i = 1:n
            inc(c, name);
        end
    end
    
    threads = list();
    threads($+1) = createThread('doIncrement', list('a', 10000));
    threads($+1) = createThread('doIncrement', list('a', 10000));
    threads($+1) = createThread('doIncrement', list('b', 10000));
    
    for i = 1:length(threads)
        waitThread(threads(i));
    end
    
    disp(c.counters);
endfunction

main();

In this Scilab version:

  1. We define a Container function that creates a structure with a semaphore (simulating a mutex) and a counters struct.

  2. The inc function locks the semaphore, increments the counter, and then unlocks the semaphore.

  3. In the main function, we create a container and define a nested function doIncrement that increments a named counter in a loop.

  4. We create three threads using createThread, each calling doIncrement with different parameters.

  5. We wait for all threads to finish using waitThread.

  6. Finally, we display the counters.

Note that Scilab doesn’t have built-in support for mutex or concurrent programming like Go does. We’re using semaphores and the createThread function to simulate similar behavior. The createThread and waitThread functions are assumed to be available; in a real Scilab environment, you might need to implement these or use a different concurrency approach.

Running the program should show that the counters are updated as expected:

a: 20000
b: 10000

This example demonstrates how to use mutex-like constructs to safely access shared data across multiple threads in Scilab.