MATLAB中Java的“同步”等价于什么?
假设我有两个计时器,它们都可以修改一个变量(即矩阵)M。如果它们同时触发,它们会同时尝试更改 M(这可能会导致错误)吗?MATLAB 会自动同步这些操作吗?
MATLAB中Java的“同步”等价于什么?
假设我有两个计时器,它们都可以修改一个变量(即矩阵)M。如果它们同时触发,它们会同时尝试更改 M(这可能会导致错误)吗?MATLAB 会自动同步这些操作吗?
Matlab 99% 是单线程的(另外 1% 与这个问题并不真正相关)。所以没有synchronized
可用的关键字。
但是,某些操作是可中断的,这意味着 GUI 回调或计时器可以在意外时间暂停操作。这可能会导致在多头系统中可以观察到的一些相同问题。
为防止中断,interruptible
请在可用时使用该属性(通常在 GUI 对象上)。这应该处理在处理 GUI 回调时防止重入行为的需要。例如
set(gcf,'Interruptible','off')
但是,这不处理与计时器相关的中断。
看起来两个定时器不能互相中断,所以不需要同步。但是,计时器可以中断主要活动。
经过一些测试后,这可能发生在文档中隐含的pause
、drawnow
、figure
或call 附近。getframe
它也可能发生在其他调用附近,包括一些 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