File: limited.rb

package info (click to toggle)
ruby-tins 1.32.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,248 kB
  • sloc: ruby: 6,659; makefile: 3
file content (50 lines) | stat: -rw-r--r-- 1,033 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require 'thread'

module Tins
  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
      @tg = ThreadGroup.new
    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
              @tg.add Thread.current
              yield
              @mutex.synchronize { @count -= 1 }
              @continue.signal
            end
            return
          else
            @continue.wait(@mutex)
          end
        end
      end
    end

    def wait
      @tg.list.each(&:join)
    end

    def process
      yield self
    ensure
      wait
    end
  end
end

require 'tins/alias'