Class: Proco::MT::Worker
- Inherits:
-
Object
- Object
- Proco::MT::Worker
- Includes:
- Threaded
- Defined in:
- lib/proco/mt/worker.rb
Instance Attribute Summary collapse
-
#counter ⇒ Object
readonly
Returns the value of attribute counter.
Instance Method Summary collapse
-
#assign(&block) ⇒ Object
Blocks when working.
- #exit ⇒ Object
-
#initialize(logger) ⇒ Worker
constructor
A new instance of Worker.
-
#try_assign(&block) ⇒ Object
Returns nil when working.
- #work ⇒ Object
Methods included from Threaded
Methods included from Base
#broadcast, #do_when, #signal, #synchronize, #try_when, #wait_until
Methods included from Logger
Constructor Details
#initialize(logger) ⇒ Worker
Returns a new instance of Worker.
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/proco/mt/worker.rb', line 9 def initialize logger super() @logger = logger @block = nil @counter = 0 spawn do work while running? end end |
Instance Attribute Details
#counter ⇒ Object (readonly)
Returns the value of attribute counter.
7 8 9 |
# File 'lib/proco/mt/worker.rb', line 7 def counter @counter end |
Instance Method Details
#assign(&block) ⇒ Object
Blocks when working
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/proco/mt/worker.rb', line 43 def assign &block #do_when(Proc.new { return unless running?; @block.nil? }) do # @block = block #end @mtx.lock while true break unless @block return unless running? @cv.wait @mtx end @block = block ensure @cv.broadcast @mtx.unlock end |
#exit ⇒ Object
75 76 77 78 |
# File 'lib/proco/mt/worker.rb', line 75 def exit wait_until { @block.nil? } super end |
#try_assign(&block) ⇒ Object
Returns nil when working
60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/proco/mt/worker.rb', line 60 def try_assign &block #try_when(Proc.new { return unless running?; @block.nil? }) do # @block = block #end return unless @mtx.try_lock begin return if !running? || @block @block = block ensure @cv.broadcast @mtx.unlock end end |
#work ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/proco/mt/worker.rb', line 21 def work # Not using do_when makes the code around the task block about 10% faster @mtx.lock while true break if @block return unless running? @cv.wait @mtx end block = @block @counter += 1 @block = nil # Release lock here, so that a new task can be assigned during the execution # 50 -> 30 @cv.broadcast @mtx.unlock # Work! block.call end |