Sha256: 744783331dab30f09de155c25be98650a1a50f5eaafc1e22ac0e6a17669eadd8

Contents?: true

Size: 833 Bytes

Versions: 17

Compression:

Stored size: 833 Bytes

Contents

require 'thread'

module Spruz
  class Limited
    # Create a Limited instance, that runs _maximum_ threads at most.
    def initialize(maximum)
      @mutex =  Mutex.new
      @continue = ConditionVariable.new
      @maximum = Integer(maximum)
      raise ArgumentError, "maximum < 1" if @maximum < 1
      @count = 0
    end

    # The maximum number of worker threads.
    attr_reader :maximum

    # Execute _maximum_ number of threads in parallel.
    def execute
      @mutex.synchronize do
        loop do
          if @count < @maximum
            @count += 1
            Thread.new do
              yield
              @mutex.synchronize { @count -= 1 }
              @continue.signal
            end
            return
          else
            @continue.wait(@mutex)
          end
        end
      end
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
spruz-0.2.13 lib/spruz/limited.rb
spruz-0.2.12 lib/spruz/limited.rb
spruz-0.2.11 lib/spruz/limited.rb
spruz-0.2.10 lib/spruz/limited.rb
spruz-0.2.9 lib/spruz/limited.rb
spruz-0.2.8 lib/spruz/limited.rb
spruz-0.2.7 lib/spruz/limited.rb
spruz-0.2.6 lib/spruz/limited.rb
spruz-0.2.5 lib/spruz/limited.rb
spruz-0.2.2 lib/spruz/limited.rb
spruz-0.2.1 lib/spruz/limited.rb
spruz-0.2.0 lib/spruz/limited.rb
spruz-0.1.5 lib/spruz/limited.rb
spruz-0.1.3 lib/spruz/limited.rb
spruz-0.1.2 lib/spruz/limited.rb
spruz-0.1.1 lib/spruz/limited.rb
spruz-0.1.0 lib/spruz/limited.rb