Class: Thpool::Worker

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pool, *args) ⇒ Worker

Creates a new worker attached to the provided pool. Optional arguments may be supplied, which are passed on to the blocks it processes.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/thpool/worker.rb', line 12

def initialize(pool, *args)
  @pool = pool
  @args = args

  @thread = Thread.new do
    Thread.abort_on_exception = true
    begin
      self.after_initialize

      while (block = @pool.block_pop)
        begin
          @block = block
          self.before_perform(block)
          perform(&block)
          self.after_perform(block)
          @block = nil

          unless (@pool.worker_needed?(self))
            @pool.worker_finished!(self)
            break
          end
        rescue => exception
          @pool.handle_exception(self, exception, block)
        end
      end
    rescue => exception
      @pool.handle_exception(self, exception, nil)
    end
  end
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



5
6
7
# File 'lib/thpool/worker.rb', line 5

def args
  @args
end

#blockObject (readonly)

Returns the value of attribute block.



6
7
8
# File 'lib/thpool/worker.rb', line 6

def block
  @block
end

#poolObject (readonly)

Properties ===========================================================



4
5
6
# File 'lib/thpool/worker.rb', line 4

def pool
  @pool
end

Instance Method Details

#after_initializeObject

This method is called after the worker is initialized within the thread used by the worker. It can be customized in sub-classes as required.



52
53
# File 'lib/thpool/worker.rb', line 52

def after_initialize
end

#after_perform(block) ⇒ Object

This method is called just after the worker has finished executing the given block This should be customized in sub-classes to do any additional processing required.



64
65
# File 'lib/thpool/worker.rb', line 64

def after_perform(block)
end

#before_perform(block) ⇒ Object

This method is called just before the worker executes the given block. This should be customized in sub-classes to do any additional processing required.



58
59
# File 'lib/thpool/worker.rb', line 58

def before_perform(block)
end

#joinObject

Called by the pool to reap this thread when it is finished.



68
69
70
# File 'lib/thpool/worker.rb', line 68

def join
  @thread.join
end

#perform {|@args| ... } ⇒ Object

Calls the Proc pulled from the queue. Subclasses can implement their own method here which might pass in arguments to the block for contextual purposes.

Yields:



46
47
48
# File 'lib/thpool/worker.rb', line 46

def perform
  yield(*@args)
end