Class: EventMachine::Synchrony::Thread::Mutex
- Inherits:
-
Object
- Object
- EventMachine::Synchrony::Thread::Mutex
- Defined in:
- lib/em-synchrony/thread.rb
Overview
Fiber-aware drop-in replacements for thread objects
Instance Method Summary collapse
- #_wakeup(fiber) ⇒ Object
-
#initialize ⇒ Mutex
constructor
A new instance of Mutex.
- #lock ⇒ Object
- #locked? ⇒ Boolean
- #sleep(timeout = nil) ⇒ Object
- #synchronize ⇒ Object
- #try_lock ⇒ Object
- #unlock ⇒ Object
Constructor Details
#initialize ⇒ Mutex
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 |
#lock ⇒ Object
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
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 |
#synchronize ⇒ Object
61 62 63 64 65 66 |
# File 'lib/em-synchrony/thread.rb', line 61 def synchronize lock yield ensure unlock end |
#try_lock ⇒ Object
48 49 50 |
# File 'lib/em-synchrony/thread.rb', line 48 def try_lock lock unless locked? end |
#unlock ⇒ Object
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 |