Class: EventMachine::Synchrony::Thread::Mutex

Inherits:
Object
  • Object
show all
Defined in:
lib/em-synchrony/thread.rb

Overview

Fiber-aware drop-in replacements for thread objects

Instance Method Summary collapse

Constructor Details

#initializeMutex

Returns a new instance of Mutex.


7
8
9
10
# File 'lib/em-synchrony/thread.rb', line 7

def initialize
  @waiters = []
  @slept = {}
end

Instance Method Details

#_wakeup(fiber) ⇒ Object


24
25
26
# File 'lib/em-synchrony/thread.rb', line 24

def _wakeup(fiber)
  fiber.resume if @slept.delete(fiber)
end

#lockObject

Raises:

  • (FiberError)

12
13
14
15
16
17
18
# File 'lib/em-synchrony/thread.rb', line 12

def lock
  current = Fiber.current
  raise FiberError if @waiters.include?(current)
  @waiters << current
  Fiber.yield unless @waiters.first == current
  true
end

#locked?Boolean

Returns:

  • (Boolean)

20
21
22
# File 'lib/em-synchrony/thread.rb', line 20

def locked?
  !@waiters.empty?
end

#sleep(timeout = nil) ⇒ Object


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/em-synchrony/thread.rb', line 28

def sleep(timeout = nil)
  unlock    
  beg = Time.now
  current = Fiber.current
  @slept[current] = true
  if timeout
    timer = EM.add_timer(timeout) do
      _wakeup(current)
    end
    Fiber.yield
    EM.cancel_timer timer # if we resumes not via timer
  else
    Fiber.yield
  end
  @slept.delete current
  yield if block_given?
  lock
  Time.now - beg
end

#synchronizeObject


61
62
63
64
65
66
# File 'lib/em-synchrony/thread.rb', line 61

def synchronize
  lock
  yield
ensure
  unlock
end

#try_lockObject


48
49
50
# File 'lib/em-synchrony/thread.rb', line 48

def try_lock
  lock unless locked?
end

#unlockObject

Raises:

  • (FiberError)

52
53
54
55
56
57
58
59
# File 'lib/em-synchrony/thread.rb', line 52

def unlock
  raise FiberError unless @waiters.first == Fiber.current  
  @waiters.shift
  unless @waiters.empty?
    EM.next_tick{ @waiters.first.resume }
  end
  self
end