Class: SafeFlock::Lockfile
- Inherits:
-
Object
- Object
- SafeFlock::Lockfile
- Defined in:
- lib/safe_flock/lockfile.rb
Defined Under Namespace
Constant Summary collapse
- @@global_mutex =
Mutex.new
- @@path_mutex =
{}
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
-
#pid ⇒ Object
readonly
Returns the value of attribute pid.
-
#thread_id ⇒ Object
readonly
Returns the value of attribute thread_id.
Instance Method Summary collapse
-
#initialize(path, max_wait: 5.0) ⇒ Lockfile
constructor
pathfull pathname of mutually agreed lock file. - #lock ⇒ Object
-
#unlock ⇒ Object
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’sLockfile.createblock terminates.
Constructor Details
#initialize(path, max_wait: 5.0) ⇒ Lockfile
path full pathname of mutually agreed lock file.
options
-
max_waitseconds to retry acquiring lock before giving up and raisingError(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
#path ⇒ Object (readonly)
Returns the value of attribute path.
54 55 56 |
# File 'lib/safe_flock/lockfile.rb', line 54 def path @path end |
#pid ⇒ Object (readonly)
Returns the value of attribute pid.
54 55 56 |
# File 'lib/safe_flock/lockfile.rb', line 54 def pid @pid end |
#thread_id ⇒ Object (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
#lock ⇒ Object
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 |
#unlock ⇒ Object
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 |