Sha256: 727c5cf6535c3689819f13da30959205b560d0aea57a8a7e3bc4c2ef90da3267

Contents?: true

Size: 1.28 KB

Versions: 40

Compression:

Stored size: 1.28 KB

Contents

# NOTE: Extracted from https://github.com/schmurfy/fiber_pool.

module OverSIP
  class 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.
    def initialize count = 100
      @fibers,@busy_fibers,@queue = [],{},[]

      count.times do |i|
        add_fiber()
      end
    end

    def add_fiber
      fiber = ::Fiber.new do |block|
        loop do
          block.call
          unless @queue.empty?
            block = @queue.shift
          else
            @busy_fibers.delete ::Fiber.current.object_id
            @fibers.unshift ::Fiber.current
            block = ::Fiber.yield
          end
        end
      end

      @fibers << fiber
      fiber
    end
    private :add_fiber

    # If there is an available fiber use it, otherwise, leave it to linger
    # in a queue.
    def spawn &block
      # resurrect dead fibers
      @busy_fibers.values.reject(&:alive?).each do |f|
        @busy_fibers.delete f.object_id
        add_fiber()
      end

      if (fiber = @fibers.shift)
        @busy_fibers[fiber.object_id] = fiber
        fiber.resume block
      else
        @queue << block
      end

      fiber
    end

  end  # class FiberPool
end

Version data entries

40 entries across 40 versions & 2 rubygems

Version Path
oversip_p-1.0.2 lib/oversip/fiber_pool.rb
oversip_p-1.0.0 lib/oversip/fiber_pool.rb
oversip-2.0.4 lib/oversip/fiber_pool.rb
oversip-2.0.3 lib/oversip/fiber_pool.rb
oversip-2.0.2 lib/oversip/fiber_pool.rb
oversip-2.0.1 lib/oversip/fiber_pool.rb
oversip-2.0.0 lib/oversip/fiber_pool.rb
oversip-1.4.1 lib/oversip/fiber_pool.rb
oversip-1.4.0 lib/oversip/fiber_pool.rb
oversip-1.3.8 lib/oversip/fiber_pool.rb
oversip-1.3.7 lib/oversip/fiber_pool.rb
oversip-1.3.6 lib/oversip/fiber_pool.rb
oversip-1.3.5 lib/oversip/fiber_pool.rb
oversip-1.3.3 lib/oversip/fiber_pool.rb
oversip-1.3.2 lib/oversip/fiber_pool.rb
oversip-1.3.1 lib/oversip/fiber_pool.rb
oversip-1.3.0 lib/oversip/fiber_pool.rb
oversip-1.3.0.dev1 lib/oversip/fiber_pool.rb
oversip-1.2.1 lib/oversip/fiber_pool.rb
oversip-1.2.0 lib/oversip/fiber_pool.rb