Class: LightIO::Library::Thread::Mutex

Inherits:
Object
  • Object
show all
Defined in:
lib/lightio/library/mutex.rb

Instance Method Summary collapse

Constructor Details

#initializeMutex

Returns a new instance of Mutex.



6
7
8
9
10
# File 'lib/lightio/library/mutex.rb', line 6

def initialize
  @queue = Queue.new
  @queue << true
  @locked_thread = nil
end

Instance Method Details

#lockObject

Raises:



12
13
14
15
16
17
# File 'lib/lightio/library/mutex.rb', line 12

def lock
  raise ThreadError, "deadlock; recursive locking" if owner?
  @queue.pop
  @locked_thread = LightIO::Thread.current
  self
end

#locked?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/lightio/library/mutex.rb', line 26

def locked?
  !@locked_thread.nil?
end

#owner?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/lightio/library/mutex.rb', line 30

def owner?
  @locked_thread == LightIO::Thread.current
end

#sleep(timeout = nil) ⇒ Object



34
35
36
37
38
# File 'lib/lightio/library/mutex.rb', line 34

def sleep(timeout=nil)
  unlock
  LightIO.sleep(timeout)
  lock
end

#synchronizeObject

Raises:



40
41
42
43
44
45
46
47
48
# File 'lib/lightio/library/mutex.rb', line 40

def synchronize
  raise ThreadError, 'must be called with a block' unless block_given?
  lock
  begin
    yield
  ensure
    unlock
  end
end

#try_lockObject



50
51
52
53
54
55
56
57
# File 'lib/lightio/library/mutex.rb', line 50

def try_lock
  if @locked_thread.nil?
    lock
    true
  else
    false
  end
end

#unlockObject

Raises:



19
20
21
22
23
24
# File 'lib/lightio/library/mutex.rb', line 19

def unlock
  raise ThreadError, "Attempt to unlock a mutex which is not locked" unless owner?
  @locked_thread = nil
  @queue << true
  self
end