Class: ParallelTasker
- Inherits:
-
Object
- Object
- ParallelTasker
- Defined in:
- lib/parallel_tasker.rb,
lib/parallel_tasker/task.rb
Overview
Run tasks in parallel threads
Defined Under Namespace
Instance Method Summary collapse
-
#add_task(id, &block) ⇒ Object
(also: #<<)
Add task to be executed.
-
#initialize(concurrency) ⇒ ParallelTasker
constructor
Set max number of parallel threads.
-
#run ⇒ Object
Execute all tasks in separate threads, with maximum asked concurrency of parallel threads.
Constructor Details
#initialize(concurrency) ⇒ ParallelTasker
Set max number of parallel threads. Yields self to block, if given. Unless block calls #run, it is called automatically.
11 12 13 14 15 16 17 18 19 |
# File 'lib/parallel_tasker.rb', line 11 def initialize concurrency @concurrency = concurrency @tasks_queue = Queue.new @already_run = false if block_given? yield self self.run unless @already_run end end |
Instance Method Details
#add_task(id, &block) ⇒ Object Also known as: <<
Add task to be executed.
22 23 24 |
# File 'lib/parallel_tasker.rb', line 22 def add_task id, &block @tasks_queue << Task.new(id, &block) end |
#run ⇒ Object
Execute all tasks in separate threads, with maximum asked concurrency of parallel threads. Returns a Hash with all given id as keys, and its value are threads themselves. User can use Thread class methods to verify each task state, such as Thread#join.
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/parallel_tasker.rb', line 34 def run raise DoubleRun.new('#run called more than one time') if @already_run @already_run = true @result = {} processor_threads = [] @concurrency.times do processor_threads << new_processor_thread end processor_threads.each{|t| t.join } @result end |