Class: Procrastinate::Utils::OneTimeFlag
- Inherits:
-
Object
- Object
- Procrastinate::Utils::OneTimeFlag
- Defined in:
- lib/procrastinate/utils/one_time_flag.rb,
lib/procrastinate/utils/one_time_flag_ruby18_shim.rb
Overview
A flag that will allow threads to wait until it is set. Once it is set, it cannot be unset.
Guarantees that this class tries to make:
1) No thread will start waiting for the flag once it is already set. There
no set-hole, meaning that no thread goes to sleep while we're waking up
threads because the flag has been set.
Candidate stdlib classes violate some of these guarantees, here are some candidates:
* ConditionVariable - violates 1)
Instance Method Summary collapse
-
#initialize ⇒ OneTimeFlag
constructor
A new instance of OneTimeFlag.
-
#set ⇒ Object
Sets the flag and releases all waiting threads.
-
#set? ⇒ Boolean
Non blocking: Is the flag set?.
-
#wait ⇒ Object
If the flag is set, does nothing.
Constructor Details
#initialize ⇒ OneTimeFlag
Returns a new instance of OneTimeFlag.
16 17 18 19 20 |
# File 'lib/procrastinate/utils/one_time_flag.rb', line 16 def initialize @waiting = [] @waiting_m = Mutex.new @set = false end |
Instance Method Details
#set ⇒ Object
Sets the flag and releases all waiting threads.
37 38 39 40 41 42 43 |
# File 'lib/procrastinate/utils/one_time_flag.rb', line 37 def set @set = true @waiting_m.synchronize do @waiting.each { |t| t.run } @waiting = [] # cleanup end end |
#set? ⇒ Boolean
Non blocking: Is the flag set?
47 48 49 |
# File 'lib/procrastinate/utils/one_time_flag.rb', line 47 def set? @set end |
#wait ⇒ Object
If the flag is set, does nothing. If it isn’t, it blocks until the flag is set.
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/procrastinate/utils/one_time_flag.rb', line 24 def wait return if set? @waiting_m.synchronize do @waiting << Thread.current until set? @waiting_m.sleep(0.001) end end end |