Class: ThreadLimiter

Inherits:
Object show all
Defined in:
lib/rwd/thread.rb

Instance Method Summary collapse

Constructor Details

#initialize(limit) ⇒ ThreadLimiter

Returns a new instance of ThreadLimiter.


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rwd/thread.rb', line 14

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

Instance Method Details

#signalObject


54
55
56
57
58
59
60
61
62
# File 'lib/rwd/thread.rb', line 54

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

    @count -= 1

    @cv.signal
  end
end

#waitObject


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rwd/thread.rb', line 38

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