Class: Concurrent::Actors::Mailbox

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/actors/mailbox.rb

Defined Under Namespace

Classes: Filter

Instance Method Summary collapse

Constructor Details

#initializeMailbox

Returns a new instance of Mailbox.



44
45
46
47
# File 'lib/concurrent/actors/mailbox.rb', line 44

def initialize
  @channel = Core::Channel.new
  @skipped = []
end

Instance Method Details

#<<(value) ⇒ Object

safe for multiple writers



50
51
52
53
# File 'lib/concurrent/actors/mailbox.rb', line 50

def <<(value)
  @channel << value
  self
end

#receiveObject

safe only for a single reader



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/concurrent/actors/mailbox.rb', line 56

def receive
  if block_given?
    filter = Filter.new
    yield filter

    value = nil
    action = nil

    found_at = nil
    @skipped.each_with_index do |obj, index|
      action = filter.action_for obj
      if action
        value = obj
        found_at = index
        break
      end
    end
    @skipped.delete_at found_at if found_at

    until action
      value = @channel.receive
      action = filter.action_for value
      @skipped.push value unless action
    end

    action.call value
  else
    unless @skipped.empty?
      @skipped.shift
    else
      @channel.receive
    end
  end
end