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:
We define a
Container
function that creates a structure with a semaphore (simulating a mutex) and a counters struct.The
inc
function locks the semaphore, increments the counter, and then unlocks the semaphore.In the
main
function, we create a container and define a nested functiondoIncrement
that increments a named counter in a loop.We create three threads using
createThread
, each callingdoIncrement
with different parameters.We wait for all threads to finish using
waitThread
.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.