我很想知道实现基于线程的队列的最佳方式是什么。
例如:
我有 10 个 Action ,我只想用 4 个线程执行。我想创建一个队列,将所有 10 个 Action 线性放置,并用 4 个线程启动前 4 个 Action ,一旦其中一个线程执行完毕,下一个线程将启动,等等 - 所以一次,线程数是4 个或小于 4 个。
最佳答案
在标准库的thread
中有一个Queue
类。使用它你可以做这样的事情:
require 'thread'
queue = Queue.new
threads = []
# add work to the queue
queue << work_unit
4.times do
threads << Thread.new do
# loop until there are no more things to do
until queue.empty?
# pop with the non-blocking flag set, this raises
# an exception if the queue is empty, in which case
# work_unit will be set to nil
work_unit = queue.pop(true) rescue nil
if work_unit
# do work
end
end
# when there is no more work, the thread will stop
end
end
# wait until all threads have completed processing
threads.each { |t| t.join }
我使用非阻塞标志 pop 的原因是在 until queue.empty?
和 pop 之间另一个线程可能已经弹出队列,所以除非非阻塞标志是设置我们可能会永远卡在那条线上。
如果您使用的是默认的 Ruby 解释器 MRI,请记住线程不会是绝对并发的。如果您的工作受 CPU 限制,您也可以运行单线程。如果你有一些阻塞 IO 的操作,你可能会得到一些并行性,但是 YMMV。或者,您可以使用允许完全并发的解释器,例如 jRuby 或 Rubinius。
关于ruby - 线程和队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6558828/