Class: Vagrant::Util::FileMutex

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/file_mutex.rb

Overview

Utility to provide a simple mutex via file lock

Instance Method Summary collapse

Constructor Details

#initialize(mutex_path) ⇒ FileMutex

Create a new FileMutex instance

Parameters:

  • mutex_path (String)

    path for file



11
12
13
# File 'lib/vagrant/util/file_mutex.rb', line 11

def initialize(mutex_path)
  @mutex_path = mutex_path
end

Instance Method Details

#lockObject

Attempt to acquire the lock



29
30
31
32
33
# File 'lib/vagrant/util/file_mutex.rb', line 29

def lock
  if lock_file.flock(File::LOCK_EX|File::LOCK_NB) === false
    raise Errors::VagrantLocked, lock_file_path: @mutex_path
  end
end

#unlockObject

Unlock the file



36
37
38
39
40
# File 'lib/vagrant/util/file_mutex.rb', line 36

def unlock
  lock_file.flock(File::LOCK_UN)
  lock_file.close
  File.delete(@mutex_path) if File.file?(@mutex_path)
end

#with_lock(&block) ⇒ Object

Execute provided block within lock and unlock when completed



17
18
19
20
21
22
23
24
25
26
# File 'lib/vagrant/util/file_mutex.rb', line 17

def with_lock(&block)
  lock
  begin
    block.call
  rescue => e
    raise e
  ensure
    unlock
  end
end