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

以前のスレッドの1つがドロップオフするまで、新しいスレッドは開始されません。誰かがこれを行うためのより良い、よりエレガントな方法を知っていますか?

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 に答える