Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/pwork/array.rb
Instance Method Summary collapse
-
#peach(thread_count = 5, &block) ⇒ Object
This method is called to loop over each item in this array in parallel threads.
-
#thread_process {|item| ... } ⇒ Object
This method is used to recursively process an item on a thread.
Instance Method Details
#peach(thread_count = 5, &block) ⇒ Object
This method is called to loop over each item in this array in parallel threads
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/pwork/array.rb', line 4 def peach(thread_count = 5, &block) @mutex = Mutex.new @index_count = -1 threads = [] thread_vars = PWork::Helpers::Threads.get_thread_vars thread_count.times.each do thread = Thread.new do PWork::Helpers::Threads.set_thread_vars(thread_vars) thread_process(&block) end threads.push(thread) end #wait for all threads to exit threads.each { |thr| thr.join } end |
#thread_process {|item| ... } ⇒ Object
This method is used to recursively process an item on a thread
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/pwork/array.rb', line 23 def thread_process(&block) item = nil #use a mutex to get the next item from the array to ensure thread safety @mutex.synchronize do @index_count += 1 if @index_count <= self.length - 1 item = self[@index_count] end end if item == nil return end #execute the block for the current item yield item #recursively attempt to process another item from the array opn this thread thread_process(&block) end |