Class: Actuator::Mutex
- Inherits:
-
Object
- Object
- Actuator::Mutex
- Defined in:
- lib/actuator/mutex.rb
Instance Method Summary collapse
- #_wake_up(job) ⇒ 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.
3 4 5 |
# File 'lib/actuator/mutex.rb', line 3 def initialize @waiters = [] end |
Instance Method Details
#_wake_up(job) ⇒ Object
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/actuator/mutex.rb', line 21 def _wake_up(job) if job.sleep_timer job.wake! elsif job.mutex_asleep job.mutex_asleep = nil job.fiber.resume else raise FiberError, "_wake_up called for job #{job.id} which is #{job.state}" end end |
#lock ⇒ Object
7 8 9 10 11 12 13 14 15 |
# File 'lib/actuator/mutex.rb', line 7 def lock job = Job.current raise FiberError if @waiters.include? job @waiters << job if @waiters.size > 1 Job.yield end true end |
#locked? ⇒ Boolean
17 18 19 |
# File 'lib/actuator/mutex.rb', line 17 def locked? !@waiters.empty? end |
#sleep(timeout = nil) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/actuator/mutex.rb', line 32 def sleep(timeout=nil) unlock if timeout Job.sleep(timeout) else job = Job.current job.mutex_asleep = self begin Job.yield ensure job.mutex_asleep = nil end end nil ensure lock end |
#synchronize ⇒ Object
68 69 70 71 72 73 |
# File 'lib/actuator/mutex.rb', line 68 def synchronize lock yield ensure unlock end |
#try_lock ⇒ Object
50 51 52 |
# File 'lib/actuator/mutex.rb', line 50 def try_lock lock unless locked? end |
#unlock ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/actuator/mutex.rb', line 54 def unlock unless @waiters.first == Job.current raise "[Job #{Job.current.id}] Mutex#unlock called from job which does not have the lock - @waiters: #{@waiters.map(&:id).inspect}" end @waiters.shift unless @waiters.empty? Actuator.next_tick do next if @waiters.empty? @waiters.first.fiber.resume end end self end |