Class: Tribe::Mailbox

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

Instance Method Summary collapse

Constructor Details

#initialize(pool) ⇒ Mailbox

Returns a new instance of Mailbox.



3
4
5
6
7
8
# File 'lib/tribe/mailbox.rb', line 3

def initialize(pool)
  @pool = pool
  @messages = []
  @alive = true
  @lock = Mutex.new
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


58
59
60
61
62
# File 'lib/tribe/mailbox.rb', line 58

def alive?
  @lock.synchronize do
    return @alive
  end
end

#killObject



49
50
51
52
53
54
55
56
# File 'lib/tribe/mailbox.rb', line 49

def kill
  @lock.synchronize do
    @alive = false
    @messages.clear
  end

  return nil
end

#obtain_and_shiftObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tribe/mailbox.rb', line 21

def obtain_and_shift
  @lock.synchronize do
    return nil unless @alive

    if @owner_thread
      if @owner_thread == Thread.current
        return @messages.shift
      else
        return nil
      end
    else
      @owner_thread = Thread.current
      return @messages.shift
    end
  end
end

#push(event, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/tribe/mailbox.rb', line 10

def push(event, &block)
  @lock.synchronize do
    return nil unless @alive

    @messages.push(event)
    @pool.perform { block.call } unless @owner_thread
  end

  return nil
end

#release(&block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/tribe/mailbox.rb', line 38

def release(&block)
  @lock.synchronize do
    return nil unless @owner_thread == Thread.current

    @owner_thread = nil
    @pool.perform { block.call } if @alive && @messages.length > 0
  end

  return nil
end