atomically creating a file lock in MATLAB (file mutex)

后端 未结 5 836
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 18:24

I am looking for a simple already implemented solution for atomically creating a file lock in MATLAB.

Something like:

file_lock(\'create\', \'mylockf         


        
5条回答
  •  感动是毒
    2021-01-18 18:46

    At the end I did one implementation based on two consecutive tests (movefile, and verify the contents of the moved file).

    not very well written, but it works for now for me.

    +++++ 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
    

    ++++++++++++++++++++++++++++++++++++++++++

提交回复
热议问题