Class: ParticlePool::PoolThread
- Inherits:
-
Object
- Object
- ParticlePool::PoolThread
- Includes:
- Comparable
- Defined in:
- lib/particle_pool/pool_thread.rb
Instance Attribute Summary collapse
-
#tasks ⇒ Object
readonly
Returns the value of attribute tasks.
Instance Method Summary collapse
- #<<(t, *args, **kwargs) ⇒ Object
- #<=>(other) ⇒ Object
-
#initialize ⇒ PoolThread
constructor
A new instance of PoolThread.
- #push(t, *args, **kwargs) ⇒ Object
- #start ⇒ Object
Constructor Details
#initialize ⇒ PoolThread
Returns a new instance of PoolThread.
6 7 8 9 |
# File 'lib/particle_pool/pool_thread.rb', line 6 def initialize @queue = Queue.new @tasks = 0 end |
Instance Attribute Details
#tasks ⇒ Object (readonly)
Returns the value of attribute tasks.
4 5 6 |
# File 'lib/particle_pool/pool_thread.rb', line 4 def tasks @tasks end |
Instance Method Details
#<<(t, *args, **kwargs) ⇒ Object
11 12 13 |
# File 'lib/particle_pool/pool_thread.rb', line 11 def <<(t, *args, **kwargs) push(t, *args, **kwargs) end |
#<=>(other) ⇒ Object
24 25 26 |
# File 'lib/particle_pool/pool_thread.rb', line 24 def <=>(other) self.tasks <=> other.tasks end |
#push(t, *args, **kwargs) ⇒ Object
15 16 17 18 19 20 21 22 |
# File 'lib/particle_pool/pool_thread.rb', line 15 def push(t, *args, **kwargs) @tasks += 1 @queue << { task: t, args: args, kwargs: kwargs } end |
#start ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/particle_pool/pool_thread.rb', line 28 def start tasks = [] iter = tasks.each loop do nt = [] shouldpop = lambda do return true unless @queue.empty? return true if tasks.empty? && nt.empty? false end shouldblock = lambda do return true if @queue.empty? && (!tasks.empty? || !nt.empty?) false end while shouldpop.() begin i = @queue.pop shouldblock.() nt << i rescue ThreadError break end end nt.each do |i| begin t = i[:task] t.start(*i[:args], **i[:kwargs]) tasks << t rescue => e puts e.backtrace puts e end end begin t = iter.next t.resume if t.done? @tasks -= 1 tasks.delete t end rescue StopIteration iter.rewind end end end |