1

我正在做很多人可能需要做的事情,处理执行时间可变的任务。我有以下概念验证代码:

threads = []

(1...10000).each do |n|
  threads << Thread.new do
    run_for = rand(10)
    puts "Starting thread #{n}(#{run_for})"
    time=Time.new
    while 1 do
      if Time.new - time >= run_for then
          break
      else
          sleep 1
      end
    end
    puts "Ending thread #{n}(#{run_for})"
  end
  finished_threads = []
  while threads.size >= 10 do
    threads.each do |t|
      finished_threads << t unless t.alive?
    end
    finished_threads.each do |t|
      threads.delete(t)
    end
  end
end

它不会启动一个新线程,直到之前的线程之一掉线。有谁知道更好,更优雅的方式来做到这一点?

4

2 回答 2

2

我建议创建一个工作池。请参阅http://snippets.dzone.com/posts/show/3276。然后将所有可变长度的工作提交到池中,并调用join以等待所有线程完成。

于 2009-11-03T00:34:10.770 回答
0

work_queue gem 是在应用程序中异步并发执行任务的最简单方法

wq = WorkQueue.new 2 # Limit the maximum number of simultaneous worker threads

(1..10_000).each do
  wq.enqueue_b do
    # Task
  end
end

wq.join # All tasks are complete after this
于 2009-11-03T00:36:55.383 回答