Class: Tins::Limited

Inherits:
Object show all
Defined in:
lib/tins/limited.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(maximum, name: nil) ⇒ Limited

Create a Limited instance, that runs maximum threads at most.

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
# File 'lib/tins/limited.rb', line 6

def initialize(maximum, name: nil)
  @maximum  = Integer(maximum)
  raise ArgumentError, "maximum < 1" if @maximum < 1
  @mutex    = Mutex.new
  @continue = ConditionVariable.new
  @name     = name
  @count    = 0
  @tg       = ThreadGroup.new
end

Instance Attribute Details

#maximumObject (readonly)

The maximum number of worker threads.



17
18
19
# File 'lib/tins/limited.rb', line 17

def maximum
  @maximum
end

Instance Method Details

#execute(&block) ⇒ Object

Execute maximum number of threads in parallel.



20
21
22
23
# File 'lib/tins/limited.rb', line 20

def execute(&block)
  @tasks or raise ArgumentError, "start processing first"
  @tasks << block
end

#processObject



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/tins/limited.rb', line 25

def process
  @tasks    = Queue.new
  @executor = create_executor
  @executor.name = @name if @name
  catch :stop do
    loop do
      yield self
    end
  ensure
    wait until done?
    @executor.kill
  end
end

#stopObject



39
40
41
# File 'lib/tins/limited.rb', line 39

def stop
  throw :stop
end