Class: Procrastinate::Utils::OneTimeFlag

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeOneTimeFlag

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

#setObject

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?

Returns:

  • (Boolean)


47
48
49
# File 'lib/procrastinate/utils/one_time_flag.rb', line 47

def set?
  @set
end

#waitObject

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