Class: ParticlePool::PoolThread

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/particle_pool/pool_thread.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePoolThread

Returns a new instance of PoolThread.



6
7
8
9
10
# File 'lib/particle_pool/pool_thread.rb', line 6

def initialize
  @queue = Queue.new
  @mtx   = Mutex.new
  @tasks = 0
end

Instance Attribute Details

#tasksObject (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



12
13
14
# File 'lib/particle_pool/pool_thread.rb', line 12

def <<(t, *args, **kwargs)
  push(t, *args, **kwargs)
end

#<=>(other) ⇒ Object



27
28
29
# File 'lib/particle_pool/pool_thread.rb', line 27

def <=>(other)
  self.tasks <=> other.tasks
end

#push(t, *args, **kwargs) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/particle_pool/pool_thread.rb', line 16

def push(t, *args, **kwargs)
  @mtx.synchronize do
    @tasks += 1
    @queue << {
      task: t,
      args: args,
      kwargs: kwargs
    }
  end
end

#startObject



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
75
76
77
# File 'lib/particle_pool/pool_thread.rb', line 31

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