Is there variable access synchronization between MATLAB main execution thread and spawned java threads?

4 views (last 30 days)
Access synchronization is not done automatically by MATLAB. This can be critical in timer callback functions and the RECORD() method of AUDIORECORDER object.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 19 Nov 2009
Variable access synchronization can be an issue when using MATLAB commands that directly or indirectly spawn child threads.
For example, a timer object is in a different thread than the MATLAB main thread. But it cannot interrupt a single MATLAB command i.e. a variable copy command.
A block of MATLAB code can be interrupted by a timer object. Thus if a block of code operates on a variable, there is a possibility of data corruption.
However, Just-in-Time compilation (JIT) can execute several lines of code all at once in certain circumstances, in which case the timer will not be able to interrupt execution. If the interruption must happen in a particular place, a DRAWNOW command will ensure that one can occur. Otherwise, the DRAWNOW is not needed.
MATLAB does not synchronize access to the variable. For example the following command will not be interrupted by a timer object.
y=x(1:1000000);
But in the case of a block of code:
y=x(1:500000);
y=[y x(500001:1000000)];
a timer shot can occur after the first statement and change "x".
To block the MATLAB command line until a timer object stops running, the WAIT() function can be used. When a timer stops running, the value of the timer object's 'running' property changes from 'on' to 'off'. If the timer is not running, WAIT() returns immediately.
In the case of the RECORD() method of the AUDIORECORDER object, RECORD() runs in a separate thread. On UNIX AUDIORECORDER is implemented in JAVA using the JAVA Sound API, and the RECORD() method is a MATLAB wrapper around a Java method which runs in a JAVA thread.
On Windows it is run in a native Windows thread. This method is used for asynchronous recording. MATLAB can query the AUDIORECORDER object through the ISRECORDING() method to check the status.
The AUDIORECORDER object can be accessed by the MATLAB main thread while the recording is going on. There is no access synchronization and there is a possibility of data corruption.
To guard against accidental data corruption, the RECORDBLOCKING() method can be used. The MATLAB main thread waits till the method returns. It is similar to calling a C-MEX function that takes a while to process before returning. This method is used for synchronous recording.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!