Sha256: 71b8a2251c79dc7e3bc255f756f21af738b403a9873936c4a53e1856a78f3c56

Contents?: true

Size: 758 Bytes

Versions: 2

Compression:

Stored size: 758 Bytes

Contents

require 'thread'
require 'thwait'

module Enumerable
  def in_threads(max_threads = 10)
    InThreads.new(self, max_threads)
  end
end

class InThreads
  def initialize(object, max_threads)
    @threads = []
    @object = object
    @max_threads = max_threads
  end

  def map(*args, &block)
    run_in_threads(:map, *args, &block)
    @threads.map(&:value)
  end

  def method_missing(method, *args, &block)
    run_in_threads(method, *args, &block)
  end

private

  def run_in_threads(method, *args, &block)
    @object.send(method, *args) do |*args|
      while @threads.count(&:alive?) >= @max_threads
        ThreadsWait.new(*@threads).next_wait
      end
      @threads << Thread.new(*args, &block)
    end
  ensure
    @threads.map(&:join)
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
in_threads-0.0.4 lib/in_threads.rb
in_threads-0.0.3 lib/in_threads.rb