ruby - 如何在 ruby​​ 中使循环多线程?

标签 ruby multithreading

如何使这些循环与 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

注意:@@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)

关于ruby - 如何在 ruby​​ 中使循环多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35693944/

相关文章:

java - Scala 反射中的线程安全与类型匹配

c++ - 使用并行线程查找所有加起来等于给定数字的组合

arrays - 检查数组中的哈希值

ruby-on-rails - rails 集成测试通过 Itest 但 "rake test:integration"未提供任何输出。虽然没有错误

c# - 使用后台线程显示 "Busy Indicator"

Python:传递函数更多信息是一件坏事吗?

创建线程

ruby-on-rails - 在 Ruby 类中干燥条件验证

ruby-on-rails - Rspec:测试实例变量的赋值

ruby - 如何组合两个 block 来简化我的代码?