Class: ThreadStorm::Worker

Inherits:
Object show all
Defined in:
lib/thread_storm/worker.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(queue, options) ⇒ Worker

Takes the threadsafe queue and options from the thread pool.



6
7
8
9
10
# File 'lib/thread_storm/worker.rb', line 6

def initialize(queue, options)
  @queue   = queue
  @options = options
  @thread  = Thread.new(self){ |me| me.run }
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



3
4
5
# File 'lib/thread_storm/worker.rb', line 3

def thread
  @thread
end

Instance Method Details

#die!Object

So the thread pool can signal this worker’s thread to end.



54
55
56
# File 'lib/thread_storm/worker.rb', line 54

def die!
  @die = true
end

#die?Boolean

True if this worker’s thread should die.

Returns:

  • (Boolean)


59
60
61
# File 'lib/thread_storm/worker.rb', line 59

def die?
  !!@die
end

#pop_and_process_executionObject

Pop an execution off the queue and process it, or pass off control to a different thread.



26
27
28
# File 'lib/thread_storm/worker.rb', line 26

def pop_and_process_execution
  execution = @queue.pop and process_execution_with_timeout(execution)
end

#process_execution(execution) ⇒ Object

Seriously, process the execution.



49
50
51
# File 'lib/thread_storm/worker.rb', line 49

def process_execution(execution)
  execution.value = execution.block.call(*execution.args)
end

#process_execution_with_timeout(execution) ⇒ Object

Process the execution, handling timeouts and exceptions.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/thread_storm/worker.rb', line 31

def process_execution_with_timeout(execution)
  execution.start!
  begin
    if timeout
      timeout_method.call(timeout){ process_execution(execution) }
    else
      process_execution(execution)
    end
  rescue Timeout::Error => e
    execution.timed_out!
  rescue Exception => e
    execution.exception = e
  ensure
    execution.finish!
  end
end

#runObject

Pop executions and process them until we’re signaled to die.



21
22
23
# File 'lib/thread_storm/worker.rb', line 21

def run
  pop_and_process_execution while not die?
end

#timeoutObject



12
13
14
# File 'lib/thread_storm/worker.rb', line 12

def timeout
  @timeout ||= @options[:timeout]
end

#timeout_methodObject



16
17
18
# File 'lib/thread_storm/worker.rb', line 16

def timeout_method
  @timeout_method ||= @options[:timeout_method]
end