Class: Thespian::Strategy::Thread

Inherits:
Object
  • Object
show all
Includes:
Interface
Defined in:
lib/thespian/strategies/thread.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Interface

#salvage_mailbox

Constructor Details

#initialize(&block) ⇒ Thread

Returns a new instance of Thread.



12
13
14
15
16
17
# File 'lib/thespian/strategies/thread.rb', line 12

def initialize(&block)
  @block        = block
  @mailbox      = []
  @mailbox_lock = Monitor.new
  @mailbox_cond = @mailbox_lock.new_cond
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



10
11
12
# File 'lib/thespian/strategies/thread.rb', line 10

def thread
  @thread
end

Instance Method Details

#<<(message) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/thespian/strategies/thread.rb', line 47

def <<(message)
  @mailbox_lock.synchronize do
    @mailbox << message
    @mailbox_cond.signal
  end
  self
end

#mailbox_sizeObject



55
56
57
58
59
# File 'lib/thespian/strategies/thread.rb', line 55

def mailbox_size
  @mailbox_lock.synchronize do
    @mailbox.size
  end
end

#messagesObject



61
62
63
64
65
# File 'lib/thespian/strategies/thread.rb', line 61

def messages
  @mailbox_lock.synchronize do
    @mailbox.dup
  end
end

#receiveObject



40
41
42
43
44
45
# File 'lib/thespian/strategies/thread.rb', line 40

def receive
  @mailbox_lock.synchronize do
    @mailbox_cond.wait_while{ @mailbox.empty? }
    @mailbox.shift
  end
end

#startObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/thespian/strategies/thread.rb', line 19

def start
  # Declare local synchronization vars.
  lock = Monitor.new
  cond = lock.new_cond
  wait = true

   # Start the thread and have it signal when it's running.
  @thread = ::Thread.new do
    lock.synchronize do
      wait = false
      cond.signal
    end
    @block.call
  end

  # Block until the thread has signaled that it's running.
  lock.synchronize do
    cond.wait_while{ wait }
  end
end

#stopObject



67
68
69
70
# File 'lib/thespian/strategies/thread.rb', line 67

def stop
  self << Stop.new
  @thread.join
end