ruby - 线程和队列

标签 ruby multithreading synchronization queue

我很想知道实现基于线程的队列的最佳方式是什么。

例如:

我有 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/

相关文章:

ruby-on-rails - 访问事件记录查询中的实例方法

ruby-on-rails - 为什么在 Rails 应用程序中呈现和重定向不会停止执行?

在 C 中创建没有 pthread_join 的线程

ios - NS条件 : wait for a specified amount of time

java - GUI 和持久后端之间的通信(在单独的线程中运行)

当网络调用完成时Java同步返回

ruby-on-rails - FrozenError - 无法修改卡住字符串(ruby 2.5+)

ruby-on-rails - 测试驱动开发?精神 split 症?我糊涂了!我应该使用什么进行测试,为什么?

multithreading - 在网络 worker 中使用谷歌地图对象?

Java:允许工作线程杀死主线程