最後我做了一個基於兩個連續測試(移動文件,並驗證移動文件的內容)的實現。
寫得不是很好,但它現在適用於我。
+++++ 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