Class: ThreadPuddle
- Inherits:
-
Object
- Object
- ThreadPuddle
- Defined in:
- lib/threadpuddle.rb
Overview
Like a smaller, lamer thread pool.
Instance Attribute Summary collapse
-
#capacity ⇒ Object
readonly
Returns the value of attribute capacity.
Instance Method Summary collapse
-
#block ⇒ Object
Blocks execution of the calling thread until there’s a free slot in the puddle.
-
#initialize(capacity, klass = Thread) ⇒ ThreadPuddle
constructor
A new instance of ThreadPuddle.
-
#join ⇒ Object
Waits for all threads in the puddle to join.
-
#kill ⇒ Object
Kills all threads in the puddle.
-
#size ⇒ Object
Number of threads currently occupying the puddle.
-
#spawn(*args, &blk) ⇒ Object
Spawns a new thread in the puddle.
Constructor Details
#initialize(capacity, klass = Thread) ⇒ ThreadPuddle
Returns a new instance of ThreadPuddle.
6 7 8 9 10 |
# File 'lib/threadpuddle.rb', line 6 def initialize capacity, klass=Thread @capacity = capacity @threads = [] @klass = klass end |
Instance Attribute Details
#capacity ⇒ Object (readonly)
Returns the value of attribute capacity.
12 13 14 |
# File 'lib/threadpuddle.rb', line 12 def capacity @capacity end |
Instance Method Details
#block ⇒ Object
Blocks execution of the calling thread until there’s a free slot in the puddle.
WARNING: there is no guarantee this will ever return.
20 21 22 23 24 25 26 27 |
# File 'lib/threadpuddle.rb', line 20 def block loop { return self if @threads.length < @capacity if @threads.any?{|t| t.join(0) } sweep end } end |
#join ⇒ Object
Waits for all threads in the puddle to join.
58 59 60 61 62 63 64 |
# File 'lib/threadpuddle.rb', line 58 def join while @threads.any? sweep @threads.each{|t| t.join rescue nil } end self end |
#kill ⇒ Object
Kills all threads in the puddle.
71 72 73 74 75 |
# File 'lib/threadpuddle.rb', line 71 def kill l = @threads.each{|t| t.kill rescue nil }.length sweep l end |
#size ⇒ Object
Number of threads currently occupying the puddle.
32 33 34 35 |
# File 'lib/threadpuddle.rb', line 32 def size sweep @threads.length end |
#spawn(*args, &blk) ⇒ Object
Spawns a new thread in the puddle.
If the puddle is full, this call blocks.
45 46 47 48 49 50 51 |
# File 'lib/threadpuddle.rb', line 45 def spawn *args, &blk #:yields: *args # wait for a slot to open block # add the new thread @threads << (t = @klass.new(*args, &blk)) t end |