Class: NeverBlock::FiberPool
- Inherits:
-
Object
- Object
- NeverBlock::FiberPool
- Defined in:
- lib/neverblock/core/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::FiberPool.new(150)
loop do
fiber_pool.spawn do
#fiber body goes here
end
end
Instance Attribute Summary collapse
-
#fibers ⇒ Object
readonly
gives access to the currently free fibers.
Instance Method Summary collapse
-
#initialize(count = 50) ⇒ FiberPool
constructor
Prepare a list of fibers that are able to run different blocks of code every time.
-
#spawn(evented = true, &block) ⇒ Object
If there is an available fiber use it, otherwise, leave it to linger in a queue.
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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/neverblock/core/pool.rb', line 34 def initialize(count = 50) @fibers,@busy_fibers,@queue = [],{},[] count.times do |i| fiber = NB::Fiber.new do |block| loop do block.call # callbacks are called in a reverse order, much like c++ destructor NB::Fiber.current[:callbacks].pop.call while NB::Fiber.current[:callbacks].length > 0 unless @queue.empty? block = @queue.shift else @busy_fibers.delete(NB::Fiber.current.object_id) @fibers << NB::Fiber.current block = NB::Fiber.yield end end end fiber[:callbacks] = [] @fibers << fiber end end |
Instance Attribute Details
#fibers ⇒ Object (readonly)
gives access to the currently free fibers
29 30 31 |
# File 'lib/neverblock/core/pool.rb', line 29 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
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/neverblock/core/pool.rb', line 58 def spawn(evented = true, &block) if fiber = @fibers.shift fiber[:callbacks] = [] @busy_fibers[fiber.object_id] = fiber fiber[:neverblock] = evented fiber.resume(block) else @queue << block end self # we are keen on hiding our queue end |