2010年11月25日木曜日

Ruby でクラス Queue を使いたいのだが

Ruby でスレッドを使って IO 処理を並列実行したい。

同時実行数を制限するため Queue や SizedQueue が使えそうだ。でもスレッドとか排他ロックに不慣れなので本や Web の解説を読んでも今ひとつピンとこない。試しに Queue の定義を覗いて見ると肝心な部分はほんの 30 行程度であった。

落ち込んだ... クールすぎて。

ruby-1.9.2p0 の thread.rb より一部(のメッソッド)抜粋。
class Queue
  #
  # Creates a new queue.
  #
  def initialize
    @que = []
    @waiting = []
    @que.taint  # enable tainted comunication
    @waiting.taint
    self.taint
    @mutex = Mutex.new
  end

  #
  # Pushes +obj+ to the queue.
  #
  def push(obj)
    @mutex.synchronize{
      @que.push obj
      begin
        t = @waiting.shift
        t.wakeup if t
      rescue ThreadError
        retry
      end
    }
  end

  #
  # Retrieves data from the queue.  If the queue is empty, the calling thread is
  # suspended until data is pushed onto the queue.  If +non_block+ is true, the
  # thread isn't suspended, and an exception is raised.
  #
  def pop(non_block=false)
    @mutex.synchronize{
      while true
        if @que.empty?
          raise ThreadError, "queue empty" if non_block
          @waiting.push Thread.current
          @mutex.sleep
        else
          return @que.shift
        end
      end
    }
  end
end

0 件のコメント:

コメントを投稿