Class: NeverBlock::Pool::FiberPool

Inherits:
Object
  • Object
show all
Defined in:
lib/never_block/pool/fiber_pool.rb

Overview

Author

Mohammad A. Ali ([email protected])

Copyright

Copyright © 2008 eSpace, Inc.

License

Distributes under the same terms as Ruby

A pool of initialized fibers It does not grow in size or create transient fibers It will queue code blocks when needed (if all its fibers are busy)

This class is particulary useful when you use the fibers to connect to evented back ends. It also does not generate transient objects and thus saves memory.

Example: fiber_pool = NeverBlock::Pool::FiberPool.new(150)

loop do

fiber_pool.spawn do
  #fiber body goes here 
end

end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count = 50) ⇒ FiberPool

Prepare a list of fibers that are able to run different blocks of code every time once a fiber is done with its block it attempts to fetch another one from the queue.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/never_block/pool/fiber_pool.rb', line 45

def initialize(count = 50)
 @fibers,@queue = [],[]
 count.times do |i| 
  fiber = Fiber.new do |block|
	  loop do
		  block.call
		  unless @queue.empty?
			  block = @queue.shift
		  else
			  block = Fiber.yield @fibers << Fiber.current
		  end
	  end
  end
  fiber[:neverblock] = true
  @fibers << fiber
 end 
end

Instance Attribute Details

#fibersObject (readonly)

gives access to the currently free fibers



37
38
39
# File 'lib/never_block/pool/fiber_pool.rb', line 37

def fibers
  @fibers
end

Instance Method Details

#spawn(evented = true, &block) ⇒ Object

If there is an available fiber use it, otherwise, leave it to linger in a queue



65
66
67
68
69
70
71
72
73
# File 'lib/never_block/pool/fiber_pool.rb', line 65

def spawn(evented = true, &block)
 if fiber = @fibers.shift
   fiber[:neverblock] = evented
  fiber.resume(block)
 else
  @queue << block
 end
 self # we are keen on hiding our queue 
end