最后我做了一个基于两个连续测试(移动文件,并验证移动文件的内容)的实现。
写得不是很好,但它现在适用于我。
+++++ file_lock.m ++++++++++++++++++++++++
function file_lock(op, filename)
%this will block until it creates the lock file:
%file_lock('create', 'mylockfile')
%
%this will remove the lock file:
%file_lock('remove', 'mylockfile')
% todo: verify that there are no bugs
filename = [filename '.mat'];
if isequal(op, 'create')
id = [tempname() '.mat']
while true
save(id, 'id');
success = fileattrib(id, '-w');
if success == 0; error('fileattrib'); end
while true
if exist(filename, 'file'); %first test
fprintf('file lock exists(1). waiting...\n');
pause(1);
continue;
end
status = movefile(id, filename); %second test
if status == 1; break; end
fprintf('file lock exists(2). waiting...\n');
pause(1);
end
temp = load(filename, 'id'); % third test.
if isequal(id, temp.id); break; end
fprintf('file lock exists(3). waiting...\n');
pause(1)
end
elseif isequal(op, 'remove')
%delete(filename);
execute_rs(@() delete(filename));
else
error('invalid op');
end
function execute_rs(f)
while true
try
lastwarn('');
f();
if ~isequal(lastwarn, ''); error(lastwarn); end %such as: Warning: File not found or permission denied
break;
catch exception
fprintf('Error: %s\n.Retrying...\n', exception.message);
pause(.5);
end
end
+++++++ +++++++++++++++++++++++
我讨厌被扫兴,但这是极难得到一个正确的一般的方式,尤其是网络文件。文件锁定与系统高度相关。没有简单的,已经实施的解决方案没有被破坏。 (不难写出“似乎主要工作”的东西;很难写出一些不会在生产中失败的东西。)让我们回过头来看看:你想要同步访问什么?它是文件内容还是文件代表其他资源?您定位的平台是什么?如何“正确”你需要排除? – 2010-08-10 21:31:43