Class: SafeFlock::Lockfile

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_flock/lockfile.rb

Defined Under Namespace

Classes: Error, Locked

Constant Summary collapse

@@global_mutex =
Mutex.new
@@path_mutex =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, max_wait: 5.0) ⇒ Lockfile

path full pathname of mutually agreed lock file.

options

  • max_wait seconds to retry acquiring lock before giving up and raising Error (5.0)



18
19
20
21
22
23
24
25
26
# File 'lib/safe_flock/lockfile.rb', line 18

def initialize(path, max_wait: 5.0)
  @pid = $$
  @thread_id = Thread.current.object_id
  @path = path
  @max_wait = max_wait
  @wait_per_try = 0.1
  @mlocked = false
  @lockfd = nil
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



54
55
56
# File 'lib/safe_flock/lockfile.rb', line 54

def path
  @path
end

#pidObject (readonly)

Returns the value of attribute pid.



54
55
56
# File 'lib/safe_flock/lockfile.rb', line 54

def pid
  @pid
end

#thread_idObject (readonly)

Returns the value of attribute thread_id.



54
55
56
# File 'lib/safe_flock/lockfile.rb', line 54

def thread_id
  @thread_id
end

Instance Method Details

#lockObject



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/safe_flock/lockfile.rb', line 28

def lock
  deadline = Time.now.to_f + @max_wait
  while !(is_locked = try_lock)
    if Time.now.to_f < deadline
      sleep @wait_per_try
    else
      break
    end
  end
  is_locked
end

#unlockObject

If the lock is inherited by a forked child process, it will hold the lock until the child calls unlock (or terminates) and the parent’s Lockfile.create block terminates. The parent should not call unlock.



44
45
46
47
48
49
50
51
52
# File 'lib/safe_flock/lockfile.rb', line 44

def unlock
  if @lockfd
    @lockfd.close
    @lockfd = nil
  end
  if @mlocked && @pid == $$ and @thread_id == Thread.current.object_id
    mutex_unlock
  end
end