Hasan
Hasan

Reputation: 564

How to make loops multithread in ruby?

How can I make these loops parallel with multithreading capability of ruby?

1.

from = 'a' * 1
to = 'z' * 3


("#{from}".."#{to}").each do |combination|  

    # ...

end

2.

@@alphabetSet_tr.length.times do |i|
    @@alphabetSet_tr.length.times do |j|
        @@alphabetSet_tr.length.times do |k|
            combination = @@alphabetSet_tr[i] + @@alphabetSet_tr[j] + @@alphabetSet_tr[k]
        end
    end
end

Note: @@alphabetSet_tr is an array which has 29 items

Upvotes: 2

Views: 2349

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37419

If you want to utilize your cores, you can use a Queue to divide the workload between a constant number of threads:

require 'thread'

queue = Queue.new

number_of_cores = 32

threads = (0..number_of_cores).map do
  Thread.new do
    combination = queue.pop
    while combination
      # do stuff with combination...

      # take the next combination from the queue
      combination = queue.pop
    end
  end
end

# fill the queue:
("#{from}".."#{to}").each do |combination|  
  queue << combination
end

# drain the threads
number_of_cores.times { queue << nil }

threads.each { |t| t.join }

If you fear that the size of the queue itself would be an issue - you can use SizedQueue which will block push operations if it gets larger than a certain size - capping its memory usage -

queue = SizedQueue.new(10000)

Upvotes: 3

Aetherus
Aetherus

Reputation: 8908

from = 'a' * 1
to = 'z' * 3


threads = ("#{from}".."#{to}").map do |combination|  
  Thread.new do
      # ...
  end
end

# In case you want the main thread waits all the child threads.
threads.each(&:join)

Upvotes: 1

Related Questions