Class: QuackConcurrency::SafeSleeper
- Defined in:
- lib/quack_concurrency/safe_sleeper.rb
Overview
A SafeSleeper can be used to safely sleep a thread or preemptively wake it.
Unlike simply calling Thread#sleep, #sleep will ensure that only calling #wake on this SafeSleeper will wake the thread. Any call to Thread#run directly, will be ignored. Threads are still be resumed if Thread#raise is called which may cause problems so it should never be used. A thread can only be put to sleep and woken once for each SafeSleeper.
Instance Method Summary collapse
-
#initialize ⇒ SafeSleeper
constructor
Creates a new SafeSleeper concurrency tool.
- #sleep(timeout = nil) ⇒ Object
- #wake ⇒ Object
Constructor Details
#initialize ⇒ SafeSleeper
Creates a new QuackConcurrency::SafeSleeper concurrency tool.
15 16 17 18 |
# File 'lib/quack_concurrency/safe_sleeper.rb', line 15 def initialize super @state = :initial end |
Instance Method Details
#sleep(timeout = nil) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/quack_concurrency/safe_sleeper.rb', line 21 def sleep(timeout = nil) timer do |start_time| deadline = wake_deadline(start_time, timeout) enforce_sleep_call_limit @mutex.synchronize do break if @state == :complete @state == :sleep wait(deadline) ensure @state = :complete end end end |
#wake ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/quack_concurrency/safe_sleeper.rb', line 36 def wake @mutex.synchronize do enforce_wake_call_limit @state = :complete @condition_variable.signal end nil end |