Class: ThreadPuddle

Inherits:
Object
  • Object
show all
Defined in:
lib/threadpuddle.rb

Overview

Like a smaller, lamer thread pool.

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#capacityObject (readonly)

Returns the value of attribute capacity.



10
11
12
# File 'lib/threadpuddle.rb', line 10

def capacity
  @capacity
end

Instance Method Details

#blockObject

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

#joinObject

Waits for all threads in the puddle to join.

Returns:

  • this ThreadPuddle object



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

#killObject

Kills all threads in the puddle.

Returns:

  • the number of threads killed



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

#sizeObject

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.

Returns:

  • the new Thread object

See Also:



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