Using File#flock as ruby global lock (mutex for processes)

ruby

Solution

When you have an exclusive lock to a file, attempting to lock it again in ruby would wait indefinitely till the file is unlocked, so you can rely on that and set a timeout on how long ruby should would wait, this might not be the most adequate way but I would do as below:

fh = File.open("/some/file/path", File::CREAT)
fh.flock(File::LOCK_EX)

require 'timeout'
def check_file_locked?(file)
  f = File.open(file, File::CREAT)
  Timeout::timeout(0.001) { f.flock(File::LOCK_EX) }
  f.flock(File::LOCK_UN)
  false
rescue 
  true
ensure
  f.close
end
f = File.open("/tmp/a.txt", "w+")
f.flock(File::LOCK_EX)
check_file_locked?("/tmp/a.txt") # => true
f.flock(File::LOCK_UN)
check_file_locked?("/tmp/a.txt") # => false 

Problem

I am having concurrency issues between two processes after short research I have seen that `temporary file` is suggested solution to this problem. So solution would be to create `/tmp/global.lock` and use it as global lock. Example of this I have found in this thread Mutex for Rails Processes Make sense to me so far, but I would like to see best practice for this solution. Above explained make sense but I wonder how to check if given file is locked? ``` fh = File.open("/some/file/path", File::CREAT) begin if locked = check_file_locked? sleep(1) else fh.flock(File::LOCK_EX) # do what you need to do end ensure fh.flock(File::LOCK_UN) end ``` This is my understanding of solution and not sure how to implement mentioned `check_file_locked?()`? Also if there is best way would love to hear it.

Original source

Related problems