MATLAB同步代码

时间:2013-03-28 22:57:46

标签: matlab synchronized

在MATLAB中,Java的“同步”等价是什么?

假设我有两个定时器,它们都可以修改变量(即矩阵)M。如果它们同时触发,它们是否会同时尝试更改M(这可能会导致错误)? MATLAB会自动同步这些操作吗?

1 个答案:

答案 0 :(得分:3)

Matlab是99%单线程(另外1%与此问题无关)。因此,没有synchronized关键字可用。

但是,某些操作是可中断的,这意味着GUI回调或定时器可以在意外时间暂停操作。这可能会导致一些在多线程系统中可以观察到的相同问题。

为防止中断,请在interruptible属性可用时使用(通常在GUI对象上)。这应该处理在处理GUI回调时防止重入行为的需要。 E.G。

set(gcf,'Interruptible','off')

但是,这不会处理与计时器相关的中断。


看来两个定时器不能互相中断,因此不需要同步。但是,计时器可以中断主要活动。

经过一些测试后,这可能发生在pausedrawnowfiguregetframe来电附近,这在文档中有所暗示。它也可以在其他调用附近发生,包括一些tic / toc调用和对Java的调用。

我不知道与定时器或函数的Interruptible属性并行,即使可能需要它。根对象0具有Interruptible属性,但它没有效果(每个文档,并已确认)。

注意:这与我之前提供的答案(见历史记录)有很大的不同,代表了最近的学习。我之前的例子使用了两个计时器,它们似乎互为冲突。此示例使用一个计时器加上主函数操作。


下面列出了一个示例,演示了一个不可中断的案例,以及两个函数some_work被中断的情况。

function minimum_synchronization_example

%Defune functions to test for interruptability
%(these are all defined at the bottom of the file)
fnList = {
    @fn_expectedNoInterruption
    @fn_expectedInterruption
    @fn_unexpectedInterruption
    };
for ix = 1:length(fnList)
    disp(['---Examples using ' func2str(fnList{ix}) '--------'])
    test_subfunction_for_interrupt_allowed(fnList{ix});
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function test_subfunction_for_interrupt_allowed(fn)
%Setup and start a timer to execute "some_work"
t1 = timer();
set(t1,...
    'Name','PerformSomeWorkTimer1', ...
    'TimerFcn', @(~,~) some_work('Timer-1', fn), ...
    'ExecutionMode','fixedSpacing', ...
    'Period', 0.4, ...
    'TasksToExecute', 6, ...
    'BusyMode', 'drop')
start(t1);

%Then immediately execute "some_work" from the main function
for ix = 1:6
    some_work('MainFun', fn);
    pause(0.2);
end

%The timer and the loop take about the same amount of time, stop and delete
%the timer before moving on
stop(t1);
delete(t1);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function some_work(displayString, subFunctionWhichMayAllowInterrupts)
%Initialize persistent, if needed.
%This records then umber of active calls to this function.
persistent entryCount
if isempty(entryCount)
    entryCount = 0;
end

%Record entry
entryCount = entryCount+1;
tic;

%Perform some work  (Inverting a 3000-by-3000 matrix takes about 1 sec on my computer)
[~] = inv(randn(3000));

%Run subfunction to see if it will be interrupted
subFunctionWhichMayAllowInterrupts();

%Display results. How many instances of this function are currently active?
if entryCount>1;
    strWarning = 'XXX ';
else
    strWarning = '    ';
end
disp([strWarning ' <' sprintf('%d',entryCount) '> [' displayString '] ; Duration: ' sprintf('%7.3f',toc)]);

%Record exit
entryCount = entryCount-1;
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function fn_expectedNoInterruption
x = 1+1;
end

function fn_expectedInterruption
drawnow;
end

function fn_unexpectedInterruption
m = java.util.HashMap();
end