Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 473
Haris Krajina Avatar asked May 19 '14 23:05

Haris Krajina


People also ask

How do you use file?

A file should not be used in a "sawing" motion (pressed back-and-forth), but rather pushed forward then lifted off the work piece each time. The cutting teeth on a file are forward-facing, which means they work only when the file is moved in that direction.

How do I use file and folder?

To open File Explorer, click the File Explorer icon on the taskbar, or double-click any folder on your desktop. A new File Explorer window will appear. Now you're ready to start working with your files and folders. From File Explorer, double-click a folder to open it.

What is an example of a file?

There are different types of files such as text files, data files, directory files, binary and graphic files, and these different types of files store different types of information. In a computer operating system, files can be stored on optical drives, hard drives or other types of storage devices.

How do I use HTML files?

The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute. Tip: Always add the <label> tag for best accessibility practices!


1 Answers

@bjhaid's answer can cause a problem with Timeout#timeout causing an interpreter error in Rubinius. It's also unnecessarily complicated.

Here's a simpler version, using a nonblocking lock instead of timeout:

def locked? lockfile_name
  f = File.open(lockfile_name, File::CREAT)

  # returns false if already locked, 0 if not
  ret = f.flock(File::LOCK_EX|File::LOCK_NB)

  # unlocks if possible, for cleanup; this is a noop if lock not acquired
  f.flock(File::LOCK_UN) 

  f.close
  !ret # ret == false means we *couldn't* get a lock, i.e. it was locked
end
like image 183
Sai Avatar answered Nov 01 '22 16:11

Sai