Sha256: 20e75e684b866a2ea3c5ab4f126df483ce52f2f728a4744c4ca2604e80570b5e

Contents?: true

Size: 992 Bytes

Versions: 2

Compression:

Stored size: 992 Bytes

Contents

require "ev/ruby"
require "thread"

class FakeThread
  def initialize(*args)
    yield(*args)
  end

  def join
  end
end

class ThreadLimiter
  def initialize(limit)
    @limit	= limit
    @count	= 0
    @threads	= []
    @mutex	= Mutex.new
    @cv		= ConditionVariable.new

    every(1) do
      @mutex.synchronize do
        @threads.dup.each do |t|
          unless t.alive?
            $stderr.puts "Found dead thread."

            @threads.delete(t)

            @count -= 1

            @cv.signal
          end
        end
      end
    end
  end

  def wait
    if block_given?
      self.wait
      yield
      self.signal
    else
      @mutex.synchronize do
        @threads << Thread.current

        @count += 1

        @cv.wait(@mutex)	if @count > @limit
      end
    end
  end

  def signal
    @mutex.synchronize do
      @threads.delete(Thread.current)

      @count -= 1

      @cv.signal
    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
rwdmovies-0.6 ev/thread.rb
rwdschedule-0.93 ev/thread.rb