When deploying Rails via Passenger or Mongrel you have multiple instances of the application running. What is the best practice or pattern to establish a mutex on shared res
If you just need to prevent multiple writers from working with a file simultaneously, you can use the File#flock
method to request an exclusive write lock from each process:
fh = File.new("/some/file/path")
begin
fh.flock(File::LOCK_EX)
# ... write to the file here, or perform some other critical operation
ensure
fh.flock(File::LOCK_UN)
end
Note: putting the unlock call in an ensure
block is important to prevent deadlock if an uncaught exception is thrown after you've locked the file.