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) ⇒ 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) ⇒ ThreadPuddle
Returns a new instance of ThreadPuddle.
5 6 7 8 |
# File 'lib/threadpuddle.rb', line 5 def initialize capacity @capacity = capacity @threads = [] end |
Instance Attribute Details
#capacity ⇒ Object (readonly)
Returns the value of attribute capacity.
10 11 12 |
# File 'lib/threadpuddle.rb', line 10 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.
18 19 20 21 22 23 24 25 |
# File 'lib/threadpuddle.rb', line 18 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.
56 57 58 59 60 61 62 |
# File 'lib/threadpuddle.rb', line 56 def join while @threads.any? sweep @threads.each{|t| t.join rescue nil } end self end |
#kill ⇒ Object
Kills all threads in the puddle.
69 70 71 72 73 |
# File 'lib/threadpuddle.rb', line 69 def kill l = @threads.each{|t| t.kill rescue nil }.length sweep l end |
#size ⇒ Object
Number of threads currently occupying the puddle.
30 31 32 33 |
# File 'lib/threadpuddle.rb', line 30 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.
43 44 45 46 47 48 49 |
# File 'lib/threadpuddle.rb', line 43 def spawn *args, &blk #:yields: *args # wait for a slot to open block # add the new thread @threads << (t = Thread.new(*args, &blk)) t end |