Class: Mutagem::Mutex

Inherits:
Lockfile show all
Defined in:
lib/mutagem/mutex.rb

Overview

File based mutex

Instance Attribute Summary

Attributes inherited from Lockfile

#lockfile

Instance Method Summary collapse

Methods inherited from Lockfile

#lock, #locked?

Constructor Details

#initialize(lockfile = 'mutagem.lck') ⇒ Mutex

Creates a new Mutex

Parameters:

  • lockfile (String) (defaults to: 'mutagem.lck')

    filename



11
12
13
# File 'lib/mutagem/mutex.rb', line 11

def initialize(lockfile='mutagem.lck')
  super lockfile
end

Instance Method Details

#execute(&block) ⇒ Boolean

Protect a block

Examples:


require 'rubygems'
require 'mutagem'

mutex = Mutagem::Mutex.new("my_process_name.lck")
mutex.execute do
  puts "this block is protected from recursion"
end

Parameters:

  • block

    the block of code to protect with the mutex

Returns:

  • (Boolean)

    0 if lock sucessful, otherwise false

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mutagem/mutex.rb', line 29

def execute(&block)
  result = false
  raise ArgumentError, "missing block" unless block_given?

  begin
    open(lockfile, 'w') do |f|
      # exclusive non-blocking lock
      result = lock(f, File::LOCK_EX | File::LOCK_NB) do |f|
        yield
      end
    end
  ensure
    # clean up but only if we have a positive result meaning we wrote the lockfile
    FileUtils.rm(lockfile) if (result && File.exists?(lockfile))
  end

  result
end