atomically creating a file lock in MATLAB (file mutex)

后端 未结 5 781
伪装坚强ぢ
伪装坚强ぢ 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:53

    Depending on which Java version you're using, perhaps this will work (translated from: http://www.javabeat.net/2007/10/locking-files-using-java/)

    classdef FileLock < handle
        properties (Access = private)
            fileLock = []
            file
        end
    
        methods
            function this = FileLock(filename)
                this.file = java.io.RandomAccessFile(filename,'rw');
                fileChannel = this.file.getChannel();
                this.fileLock = fileChannel.tryLock();
            end
    
            function val = hasLock(this)
                if ~isempty(this.fileLock) && this.fileLock.isValid()
                    val = true;
                else
                    val = false;
                end
            end
    
            function delete(this)
                this.release();
            end
    
            function release(this)
                if this.hasLock
                    this.fileLock.release();
                end
                this.file.close
            end
        end
    end
    

    Usage would be:

    lock = FileLock('my_lock_file');
    if lock.hasLock
        %// do something here
    else
        %// I guess not
    end
    %// Manually release the lock, or just delete (or let matlab clean it up)
    

    I like the obj wrapping pattern for IO so that releasing happens even in exceptions

    EDIT: The file ref must be kept around and manually closed or you won't be able to edit this. That means this code is only really useful for pure lock files, I think.

提交回复
热议问题