Sha256: c01ef87ccb7bdfc81fb7320784cabe77aa7a6bd7763b07ee9eb0be7e5b2ed3b0

Contents?: true

Size: 934 Bytes

Versions: 44

Compression:

Stored size: 934 Bytes

Contents

require "lib/rwd/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

44 entries across 44 versions & 15 rubygems

Version Path
rwdtorrent-0.08 lib/rwd/thread.rb
tinkerbell-0.03 lib/rwd/thread.rb
tinkerbell-0.01 lib/rwd/thread.rb
tinkerbell-0.04 lib/rwd/thread.rb