Class: Farce::Concurrent::Event

Inherits:
Object
  • Object
show all
Includes:
Internal::Noncopyable, Shareable::Delegated
Defined in:
lib/farce/concurrent/event.rb

Overview

A replacement for concurrent-ruby's Event implementation.

Instance Method Summary collapse

Methods included from Internal::Noncopyable

#duplicable?

Methods included from Shareable

#ractor_shareable?

Constructor Details

#initialize ⇒ Event

Returns a new instance of Event.



13
14
15
16
17
# File 'lib/farce/concurrent/event.rb', line 13

def initialize
  # Odd generations are set. Even generations are reset without forgetting earlier signals.
  @state = Strict::Atom.new(0)
  super
end

Instance Method Details

#reset ⇒ true

Returns always returns true.

Returns:

  • (true) —

    always returns true.



41
42
43
44
# File 'lib/farce/concurrent/event.rb', line 41

def reset # rubocop:disable Naming/PredicateMethod
  @state.update { |current| current.odd? ? current + 1 : current }
  true
end

#set ⇒ true

Sets the event.

Returns:

  • (true) —

    always returns true.



24
25
26
27
# File 'lib/farce/concurrent/event.rb', line 24

def set # rubocop:disable Naming/PredicateMethod
  try?
  true
end

#set? ⇒ Boolean

Returns whether the event is currently set.

Returns:

  • (Boolean) —

    whether the event is currently set.



20
# File 'lib/farce/concurrent/event.rb', line 20

def set? = @state.value.odd?

#try? ⇒ Boolean

Returns true if the event was successfully set, false otherwise.

Returns:

  • (Boolean) —

    true if the event was successfully set, false otherwise.



30
31
32
33
34
35
36
37
38
# File 'lib/farce/concurrent/event.rb', line 30

def try?
  changed = false
  @state.update do |current|
    next current if current.odd?
    changed = true
    current + 1
  end
  changed
end

#wait(timeout = nil) ⇒ Boolean

Waits for the event to be set or for the specified timeout to elapse. Resetting the event does not retract a signal already sent to current waiters.

Parameters:

  • timeout (Numeric, nil) (defaults to: nil) —

    the maximum number of seconds to wait, or nil to wait indefinitely.

Returns:

  • (Boolean) —

    true if the event was set, false if the timeout elapsed.



50
51
52
53
54
55
# File 'lib/farce/concurrent/event.rb', line 50

def wait(timeout = nil) # rubocop:disable Naming/PredicateMethod
  deadline = Internal.timeout_deadline(timeout)
  observed = @state.value
  return true if observed.odd?
  !!@state.wait_until_changed(observed, timeout: Clock.remaining(deadline))
end