Module: SafeFlock

Defined in:
lib/safe_flock.rb,
lib/safe_flock/version.rb,
lib/safe_flock/lockfile.rb

Overview

Thread-safe, transferable, flock-based lock file

Defined Under Namespace

Classes: Locked, Lockfile

Constant Summary collapse

VERSION =

Library version

Semantically versioned, see /.

"0.1.1"

Class Method Summary collapse

Class Method Details

.create(path, max_wait: 5.0) ⇒ Object

Ensure mutual exclusion of a block with flock

  • The block is only executed if the lock can be acquired.

  • The lock is held for the duration of the block.

  • Any child process forked within the block holds the lock until it terminates or explicitly releases the lock (see SafeFlock::Lockfile#unlock}).

  • No other thread may enter the block while the lock is held.

  • The lock file may be left in place after the lock is released, but this behaviour should not be relied upon.

TODO implement configurable retry

Parameters:

  • path (String)

    path of file to flock (created if necessary). Absolute pathname (see Pathname#realpath) recommended for per-path thread mutex and for processes in which the present working directory (see Dir.chdir) changes.

  • options (Hash)

    a customizable set of options

Returns:

  • (Object)

    the value of the block

Raises:

  • (SafeFlock::Locked)

    if the lock could not be acquired. If +max_wait is zero, the file was already locked. Otherwise, timed out waiting for the lock.

  • (Exception)

    if an IO error occurs opening the lock file e.g. Errno::EACCES



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/safe_flock.rb', line 45

def self.create(path, max_wait: 5.0)
  raise(ArgumentError, "Block required") unless block_given?
  lockfile = Lockfile.new(path, max_wait: max_wait)
  begin
    if lockfile.lock
      begin
        yield lockfile
      ensure
        lockfile.unlock
      end
    else
      raise Locked, "Timed out waiting for lock"
    end
  end
end