Thread and Queue

前端 未结 6 1475
情深已故
情深已故 2020-12-24 12:28

I am interested in knowing what would be the best way to implement a thread based queue.

For example:

I have 10 actions which I want to execute with only 4 t

6条回答
  •  醉话见心
    2020-12-24 12:46

    There is a Queue class in thread in the standard library. Using that you can do something like this:

    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 }
    

    The reason I pop with the non-blocking flag is that between the until queue.empty? and the pop another thread may have pop'ed the queue, so unless the non-blocking flag is set we could get stuck at that line forever.

    If you're using MRI, the default Ruby interpreter, bear in mind that threads will not be absolutely concurrent. If your work is CPU bound you may just as well run single threaded. If you have some operation that blocks on IO you may get some parallelism, but YMMV. Alternatively, you can use an interpreter that allows full concurrency, such as jRuby or Rubinius.

提交回复
热议问题