Ruby互斥的文件互斥锁

时间:2019-08-24 17:56:18

标签: ruby mutex

我想将基于文件的互斥锁设置为通用实用程序,即,我不想在各处复制并粘贴相同的代码。我只想使用文件的存在来表示锁定。如果两个过程恰好同时击中这一点,一赢一输吗?如果没有,该怎么办,我确保只有一个进程可以创建一个文件:

def lock what
    # return true on success, false on failure
    # failure means something has already claimed the mutex
    if File.exist? ("tmp/#{what}")
        return false
    else
        # create it
        file = File.open("tmp/#{what}", "w")
        file.close
        return true
    end
end

现在要解锁,只需将其删除

def unlock what
    if File.exist("tmp/#{what}"
        File.delete("tmp/#{what}"
    end
end

我不想使用块的原因是,我可以拥有一个可以跨进程工作的通用锁定文件互斥量。

if lock("process a file")
    # proceed to do something mutexy
    # and unlock when done
    unlock("process a file")
end

这项工作有效吗?如果两个进程恰好同时锁定,一赢一输?如果没有,我如何确保一个人赢了一个人输了?

0 个答案:

没有答案