Class: POSIX::Semaphore::Mutex

Inherits:
Object
  • Object
show all
Defined in:
lib/posix/semaphore/mutex.rb

Overview

Mutex provides a simple wrapper to provide a POSIX-based version of Ruby’s built-in Mutex class.

All you need to do to switch from using Ruby’s Mutex to using this is change Mutex.new to POSIX::Semaphore::Mutex.new, providing options that are the same as those to POSIX::Semaphore.new.

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Mutex

Returns a new instance of Mutex.



11
12
13
14
# File 'lib/posix/semaphore/mutex.rb', line 11

def initialize *args
  @semaphore = Semaphore.new *args
  @have_lock = false
end

Instance Method Details

#lock(*a) ⇒ Object

Raises:

  • (ThreadError)


16
17
18
19
20
# File 'lib/posix/semaphore/mutex.rb', line 16

def lock *a
  raise ThreadError, 'this mutex is already locked to us' if @have_lock
  @semaphore.wait *a
  @have_lock = true
end

#locked?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/posix/semaphore/mutex.rb', line 21

def locked?
  @have_lock or @semaphore.locked?
end

#synchronize(*a) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/posix/semaphore/mutex.rb', line 25

def synchronize *a
  lock *a
  begin
    yield
  ensure
    unlock
  end
end

#try_lockObject

Raises:

  • (ThreadError)


34
35
36
37
38
39
40
41
42
# File 'lib/posix/semaphore/mutex.rb', line 34

def try_lock
  raise ThreadError, 'this mutex is already locked to us' if @have_lock
  begin
    @semaphore.wait_nonblock
  rescue Errno::EAGAIN
    return false
  end
  return (@have_lock = true)
end

#unlockObject



44
45
46
47
# File 'lib/posix/semaphore/mutex.rb', line 44

def unlock
  @semaphore.post
  @have_lock = false
end