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, 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

#capacityObject (readonly)

Returns the value of attribute capacity.



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

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.



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

#joinObject

Waits for all threads in the puddle to join.

Returns:

  • this ThreadPuddle object



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

#killObject

Kills all threads in the puddle.

Returns:

  • the number of threads killed



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

#sizeObject

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.

Returns:

  • the new Thread object

See Also:



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