Class: InThreads::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/in_threads.rb

Overview

Thread pool

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(thread_count) ⇒ Pool

Returns a new instance of Pool.



178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/in_threads.rb', line 178

def initialize(thread_count)
  @queue = Queue.new
  @mutex = Mutex.new
  @pool = Array.new(thread_count) do
    Thread.new do
      while (block = @queue.pop)
        block.call
        break if stop?
      end
    end
  end
end

Instance Attribute Details

#exceptionObject (readonly)

Returns the value of attribute exception.



176
177
178
# File 'lib/in_threads.rb', line 176

def exception
  @exception
end

Instance Method Details

#catchObject



209
210
211
212
213
214
# File 'lib/in_threads.rb', line 209

def catch
  yield
rescue Exception => e
  @mutex.synchronize{ @exception ||= e } unless @exception
  nil
end

#finalizeObject



203
204
205
206
207
# File 'lib/in_threads.rb', line 203

def finalize
  @pool.
    each{ @queue.push(nil) }.
    each(&:join)
end

#run(&block) ⇒ Object



191
192
193
# File 'lib/in_threads.rb', line 191

def run(&block)
  @queue.push(block)
end

#stop!Object



199
200
201
# File 'lib/in_threads.rb', line 199

def stop!
  @stop = true
end

#stop?Boolean

Returns:

  • (Boolean)


195
196
197
# File 'lib/in_threads.rb', line 195

def stop?
  @stop || @exception
end