Class: LittleGhost::Support::SerializedDispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/little_ghost/support/serialized_dispatcher.rb

Overview

:nodoc:

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(&callback) ⇒ SerializedDispatcher

Returns a new instance of SerializedDispatcher.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
# File 'lib/little_ghost/support/serialized_dispatcher.rb', line 8

def initialize(&callback)
  raise ArgumentError, "callback is required" unless callback

  @callback = callback
  @mutex = Mutex.new
  @queue = []
  @draining = false
  @owner = nil
  @failure = nil
end

Instance Method Details

#call(value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/little_ghost/support/serialized_dispatcher.rb', line 19

def call(value)
  entry = Entry.new(value, ConditionVariable.new, false, nil)
  identity = [Thread.current, Fiber.current]
  @mutex.synchronize do
    raise @failure if @failure

    @queue << entry
    if @draining
      return value if @owner == identity

      entry.condition.wait(@mutex) until entry.finished
      raise entry.error if entry.error

      return value
    end

    @draining = true
    @owner = identity
  end

  drain_queue
  raise entry.error if entry.error

  value
end