Sha256: f46bdb26a35d92917adb91be8868de67311bde9820462a875a7475ae754d65c1
Contents?: true
Size: 1.2 KB
Versions: 2
Compression:
Stored size: 1.2 KB
Contents
# frozen_string_literal: true module Polyphony # Implements a limited resource pool class ResourcePool attr_reader :limit, :size # Initializes a new resource pool # @param opts [Hash] options # @param &block [Proc] allocator block def initialize(opts, &block) @allocator = block @limit = opts[:limit] || 4 @size = 0 @stock = Polyphony::Queue.new @acquired_resources = {} end def available @stock.size end def acquire fiber = Fiber.current return @acquired_resources[fiber] if @acquired_resources[fiber] add_to_stock if @size < @limit && @stock.empty? resource = @stock.shift @acquired_resources[fiber] = resource yield resource ensure @acquired_resources.delete(fiber) @stock.push resource if resource end def method_missing(sym, *args, &block) acquire { |r| r.send(sym, *args, &block) } end def respond_to_missing?(*_args) true end # Allocates a resource # @return [any] allocated resource def add_to_stock @size += 1 @stock << @allocator.call end def preheat! add_to_stock while @size < @limit end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
polyphony-0.43.10 | lib/polyphony/core/resource_pool.rb |
polyphony-0.43.9 | lib/polyphony/core/resource_pool.rb |