如何使这些循环与 ruby 的多线程功能并行?
1.
from = 'a' * 1
to = 'z' * 3
("#{from}".."#{to}").each do |combination|
# ...
end
阿拉伯数字。
@@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
注意:@@alphabetSet_tr是一个包含 29 个项目的数组
如果要
利用内核,可以使用Queue
在恒定数量的线程之间分配工作负载:
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 }
如果您担心队列本身的大小会是一个问题 - 您可以使用SizedQueue
如果它大于特定大小,它将阻止推送操作 - 限制其内存使用量 -
queue = SizedQueue.new(10000)
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)